PageRenderTime 434ms CodeModel.GetById 32ms RepoModel.GetById 2ms app.codeStats 2ms

/linkedfs/usr/lib/perl5/vendor_perl/5.8.6/i386-linux/DBI.pm

https://bitbucket.org/harakiri/trk
Perl | 7160 lines | 6033 code | 994 blank | 133 comment | 442 complexity | 81a020ca5ba4aa7046b23fda929c7b40 MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0
  1. # $Id: DBI.pm,v 11.43 2004/02/01 11:16:16 timbo Exp $
  2. # vim: ts=8:sw=4
  3. #
  4. # Copyright (c) 1994-2004 Tim Bunce Ireland
  5. #
  6. # See COPYRIGHT section in pod text below for usage and distribution rights.
  7. #
  8. require 5.006_00;
  9. BEGIN {
  10. $DBI::VERSION = "1.47"; # ==> ALSO update the version in the pod text below!
  11. }
  12. =head1 NAME
  13. DBI - Database independent interface for Perl
  14. =head1 SYNOPSIS
  15. use DBI;
  16. @driver_names = DBI->available_drivers;
  17. @data_sources = DBI->data_sources($driver_name, \%attr);
  18. $dbh = DBI->connect($data_source, $username, $auth, \%attr);
  19. $rv = $dbh->do($statement);
  20. $rv = $dbh->do($statement, \%attr);
  21. $rv = $dbh->do($statement, \%attr, @bind_values);
  22. $ary_ref = $dbh->selectall_arrayref($statement);
  23. $hash_ref = $dbh->selectall_hashref($statement, $key_field);
  24. $ary_ref = $dbh->selectcol_arrayref($statement);
  25. $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
  26. @row_ary = $dbh->selectrow_array($statement);
  27. $ary_ref = $dbh->selectrow_arrayref($statement);
  28. $hash_ref = $dbh->selectrow_hashref($statement);
  29. $sth = $dbh->prepare($statement);
  30. $sth = $dbh->prepare_cached($statement);
  31. $rc = $sth->bind_param($p_num, $bind_value);
  32. $rc = $sth->bind_param($p_num, $bind_value, $bind_type);
  33. $rc = $sth->bind_param($p_num, $bind_value, \%attr);
  34. $rv = $sth->execute;
  35. $rv = $sth->execute(@bind_values);
  36. $rv = $sth->execute_array(\%attr, ...);
  37. $rc = $sth->bind_col($col_num, \$col_variable);
  38. $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
  39. @row_ary = $sth->fetchrow_array;
  40. $ary_ref = $sth->fetchrow_arrayref;
  41. $hash_ref = $sth->fetchrow_hashref;
  42. $ary_ref = $sth->fetchall_arrayref;
  43. $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
  44. $hash_ref = $sth->fetchall_hashref( $key_field );
  45. $rv = $sth->rows;
  46. $rc = $dbh->begin_work;
  47. $rc = $dbh->commit;
  48. $rc = $dbh->rollback;
  49. $quoted_string = $dbh->quote($string);
  50. $rc = $h->err;
  51. $str = $h->errstr;
  52. $rv = $h->state;
  53. $rc = $dbh->disconnect;
  54. I<The synopsis above only lists the major methods and parameters.>
  55. =head2 GETTING HELP
  56. If you have questions about DBI, or DBD driver modules, you can get
  57. help from the I<dbi-users@perl.org> mailing list. You can get help
  58. on subscribing and using the list by emailing I<dbi-users-help@perl.org>.
  59. (To help you make the best use of the dbi-users mailing list,
  60. and any other lists or forums you may use, I I<strongly>
  61. recommend that you read "How To Ask Questions The Smart Way"
  62. by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>)
  63. The DBI home page at L<http://dbi.perl.org/> is always worth a visit
  64. and includes an FAQ and links to other resources.
  65. Before asking any questions, reread this document, consult the
  66. archives and read the DBI FAQ. The archives are listed
  67. at the end of this document and on the DBI home page.
  68. An FAQ is installed as a L<DBI::FAQ> module so
  69. you can read it by executing C<perldoc DBI::FAQ>.
  70. However the DBI::FAQ module is currently (2004) outdated relative
  71. to the online FAQ on the DBI home page.
  72. This document often uses terms like I<references>, I<objects>,
  73. I<methods>. If you're not familar with those terms then it would
  74. be a good idea to read at least the following perl manuals first:
  75. L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>.
  76. Please note that Tim Bunce does not maintain the mailing lists or the
  77. web page (generous volunteers do that). So please don't send mail
  78. directly to him; he just doesn't have the time to answer questions
  79. personally. The I<dbi-users> mailing list has lots of experienced
  80. people who should be able to help you if you need it. If you do email
  81. Tim he's very likely to just forward it to the mailing list.
  82. =head2 NOTES
  83. This is the DBI specification that corresponds to the DBI version 1.47.
  84. The DBI is evolving at a steady pace, so it's good to check that
  85. you have the latest copy.
  86. The significant user-visible changes in each release are documented
  87. in the L<DBI::Changes> module so you can read them by executing
  88. C<perldoc DBI::Changes>.
  89. Some DBI changes require changes in the drivers, but the drivers
  90. can take some time to catch up. Newer versions of the DBI have
  91. added features that may not yet be supported by the drivers you
  92. use. Talk to the authors of your drivers if you need a new feature
  93. that's not yet supported.
  94. Features added after DBI 1.21 (February 2002) are marked in the
  95. text with the version number of the DBI release they first appeared in.
  96. Extensions to the DBI API often use the C<DBIx::*> namespace.
  97. See L</Naming Conventions and Name Space>. DBI extension modules
  98. can be found at L<http://search.cpan.org/search?mode=module&query=DBIx>.
  99. And all modules related to the DBI can be found at
  100. L<http://search.cpan.org/search?query=DBI&mode=all>.
  101. =cut
  102. # The POD text continues at the end of the file.
  103. package DBI;
  104. use Carp();
  105. use DynaLoader ();
  106. use Exporter ();
  107. BEGIN {
  108. @ISA = qw(Exporter DynaLoader);
  109. # Make some utility functions available if asked for
  110. @EXPORT = (); # we export nothing by default
  111. @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags:
  112. %EXPORT_TAGS = (
  113. sql_types => [ qw(
  114. SQL_GUID
  115. SQL_WLONGVARCHAR
  116. SQL_WVARCHAR
  117. SQL_WCHAR
  118. SQL_BIT
  119. SQL_TINYINT
  120. SQL_LONGVARBINARY
  121. SQL_VARBINARY
  122. SQL_BINARY
  123. SQL_LONGVARCHAR
  124. SQL_UNKNOWN_TYPE
  125. SQL_ALL_TYPES
  126. SQL_CHAR
  127. SQL_NUMERIC
  128. SQL_DECIMAL
  129. SQL_INTEGER
  130. SQL_SMALLINT
  131. SQL_FLOAT
  132. SQL_REAL
  133. SQL_DOUBLE
  134. SQL_DATETIME
  135. SQL_DATE
  136. SQL_INTERVAL
  137. SQL_TIME
  138. SQL_TIMESTAMP
  139. SQL_VARCHAR
  140. SQL_BOOLEAN
  141. SQL_UDT
  142. SQL_UDT_LOCATOR
  143. SQL_ROW
  144. SQL_REF
  145. SQL_BLOB
  146. SQL_BLOB_LOCATOR
  147. SQL_CLOB
  148. SQL_CLOB_LOCATOR
  149. SQL_ARRAY
  150. SQL_ARRAY_LOCATOR
  151. SQL_MULTISET
  152. SQL_MULTISET_LOCATOR
  153. SQL_TYPE_DATE
  154. SQL_TYPE_TIME
  155. SQL_TYPE_TIMESTAMP
  156. SQL_TYPE_TIME_WITH_TIMEZONE
  157. SQL_TYPE_TIMESTAMP_WITH_TIMEZONE
  158. SQL_INTERVAL_YEAR
  159. SQL_INTERVAL_MONTH
  160. SQL_INTERVAL_DAY
  161. SQL_INTERVAL_HOUR
  162. SQL_INTERVAL_MINUTE
  163. SQL_INTERVAL_SECOND
  164. SQL_INTERVAL_YEAR_TO_MONTH
  165. SQL_INTERVAL_DAY_TO_HOUR
  166. SQL_INTERVAL_DAY_TO_MINUTE
  167. SQL_INTERVAL_DAY_TO_SECOND
  168. SQL_INTERVAL_HOUR_TO_MINUTE
  169. SQL_INTERVAL_HOUR_TO_SECOND
  170. SQL_INTERVAL_MINUTE_TO_SECOND
  171. ) ],
  172. sql_cursor_types => [ qw(
  173. SQL_CURSOR_FORWARD_ONLY
  174. SQL_CURSOR_KEYSET_DRIVEN
  175. SQL_CURSOR_DYNAMIC
  176. SQL_CURSOR_STATIC
  177. SQL_CURSOR_TYPE_DEFAULT
  178. ) ], # for ODBC cursor types
  179. utils => [ qw(
  180. neat neat_list $neat_maxlen dump_results looks_like_number
  181. data_string_diff data_string_desc data_diff
  182. ) ],
  183. profile => [ qw(
  184. dbi_profile dbi_profile_merge dbi_time
  185. ) ], # notionally "in" DBI::Profile and normally imported from there
  186. );
  187. $DBI::dbi_debug = 0;
  188. $DBI::neat_maxlen = 400;
  189. # If you get an error here like "Can't find loadable object ..."
  190. # then you haven't installed the DBI correctly. Read the README
  191. # then install it again.
  192. if ( $ENV{DBI_PUREPERL} ) {
  193. eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1;
  194. require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2;
  195. $DBI::PurePerl ||= 0; # just to silence "only used once" warnings
  196. }
  197. else {
  198. bootstrap DBI;
  199. }
  200. $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
  201. Exporter::export_ok_tags(keys %EXPORT_TAGS);
  202. }
  203. # Alias some handle methods to also be DBI class methods
  204. for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) {
  205. no strict;
  206. *$_ = \&{"DBD::_::common::$_"};
  207. }
  208. use strict;
  209. DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
  210. $DBI::connect_via = "connect";
  211. # check if user wants a persistent database connection ( Apache + mod_perl )
  212. if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
  213. $DBI::connect_via = "Apache::DBI::connect";
  214. DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n");
  215. }
  216. %DBI::installed_drh = (); # maps driver names to installed driver handles
  217. # Setup special DBI dynamic variables. See DBI::var::FETCH for details.
  218. # These are dynamically associated with the last handle used.
  219. tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list
  220. tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list
  221. tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean
  222. tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
  223. tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg
  224. sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  225. sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
  226. { # used to catch DBI->{Attrib} mistake
  227. sub DBI::DBI_tie::TIEHASH { bless {} }
  228. sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");}
  229. *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE;
  230. }
  231. tie %DBI::DBI => 'DBI::DBI_tie';
  232. # --- Driver Specific Prefix Registry ---
  233. my $dbd_prefix_registry = {
  234. ad_ => { class => 'DBD::AnyData', },
  235. ado_ => { class => 'DBD::ADO', },
  236. best_ => { class => 'DBD::BestWins', },
  237. csv_ => { class => 'DBD::CSV', },
  238. db2_ => { class => 'DBD::DB2', },
  239. dbi_ => { class => 'DBI', },
  240. dbm_ => { class => 'DBD::DBM', },
  241. df_ => { class => 'DBD::DF', },
  242. f_ => { class => 'DBD::File', },
  243. file_ => { class => 'DBD::TextFile', },
  244. ib_ => { class => 'DBD::InterBase', },
  245. ing_ => { class => 'DBD::Ingres', },
  246. ix_ => { class => 'DBD::Informix', },
  247. jdbc_ => { class => 'DBD::JDBC', },
  248. msql_ => { class => 'DBD::mSQL', },
  249. mysql_ => { class => 'DBD::mysql', },
  250. mx_ => { class => 'DBD::Multiplex', },
  251. nullp_ => { class => 'DBD::NullP', },
  252. odbc_ => { class => 'DBD::ODBC', },
  253. ora_ => { class => 'DBD::Oracle', },
  254. pg_ => { class => 'DBD::Pg', },
  255. proxy_ => { class => 'DBD::Proxy', },
  256. rdb_ => { class => 'DBD::RDB', },
  257. sapdb_ => { class => 'DBD::SAP_DB', },
  258. solid_ => { class => 'DBD::Solid', },
  259. sponge_ => { class => 'DBD::Sponge', },
  260. sql_ => { class => 'SQL::Statement', },
  261. syb_ => { class => 'DBD::Sybase', },
  262. tdat_ => { class => 'DBD::Teradata', },
  263. tmpl_ => { class => 'DBD::Template', },
  264. tmplss_ => { class => 'DBD::TemplateSS', },
  265. tuber_ => { class => 'DBD::Tuber', },
  266. uni_ => { class => 'DBD::Unify', },
  267. xbase_ => { class => 'DBD::XBase', },
  268. xl_ => { class => 'DBD::Excel', },
  269. };
  270. sub dump_dbd_registry {
  271. require Data::Dumper;
  272. local $Data::Dumper::Sortkeys=1;
  273. local $Data::Dumper::Indent=1;
  274. print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]);
  275. }
  276. # --- Dynamically create the DBI Standard Interface
  277. my $keeperr = { O=>0x0004 };
  278. %DBI::DBI_methods = ( # Define the DBI interface methods per class:
  279. common => { # Interface methods common to all DBI handle classes
  280. 'DESTROY' => $keeperr,
  281. 'CLEAR' => $keeperr,
  282. 'EXISTS' => $keeperr,
  283. 'FETCH' => { O=>0x0404 },
  284. 'FIRSTKEY' => $keeperr,
  285. 'NEXTKEY' => $keeperr,
  286. 'STORE' => { O=>0x0418 | 0x4 },
  287. _not_impl => undef,
  288. can => { O=>0x0100 }, # special case, see dispatch
  289. debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace
  290. dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 },
  291. err => $keeperr,
  292. errstr => $keeperr,
  293. state => $keeperr,
  294. func => { O=>0x0006 },
  295. parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 },
  296. parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 },
  297. private_data => { U =>[1,1], O=>0x0004 },
  298. set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 },
  299. trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 },
  300. trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 },
  301. swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] },
  302. },
  303. dr => { # Database Driver Interface
  304. 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
  305. 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
  306. 'disconnect_all'=>{ U =>[1,1], O=>0x0800 },
  307. data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 },
  308. default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] },
  309. },
  310. db => { # Database Session Class Interface
  311. data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 },
  312. take_imp_data => { U =>[1,1], },
  313. clone => { U =>[1,1,''] },
  314. connected => { O=>0x0100 },
  315. begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 },
  316. commit => { U =>[1,1], O=>0x0480|0x0800 },
  317. rollback => { U =>[1,1], O=>0x0480|0x0800 },
  318. 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 },
  319. last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 },
  320. preparse => { }, # XXX
  321. prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0x2200 },
  322. prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0x2200 },
  323. selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  324. selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  325. selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  326. selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  327. selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  328. selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
  329. ping => { U =>[1,1], O=>0x0404 },
  330. disconnect => { U =>[1,1], O=>0x0400|0x0800 },
  331. quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 },
  332. quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 },
  333. rows => $keeperr,
  334. tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 },
  335. table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x0800 },
  336. column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x0800 },
  337. primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x0800 },
  338. primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 },
  339. foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x0800 },
  340. type_info_all => { U =>[1,1], O=>0x2200|0x0800 },
  341. type_info => { U =>[1,2,'$data_type'], O=>0x2200 },
  342. get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 },
  343. },
  344. st => { # Statement Class Interface
  345. bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] },
  346. bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] },
  347. bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] },
  348. bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] },
  349. execute => { U =>[1,0,'[@args]'], O=>0x1040 },
  350. bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] },
  351. bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] },
  352. execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040 },
  353. execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040 },
  354. fetch => undef, # alias for fetchrow_arrayref
  355. fetchrow_arrayref => undef,
  356. fetchrow_hashref => undef,
  357. fetchrow_array => undef,
  358. fetchrow => undef, # old alias for fetchrow_array
  359. fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] },
  360. fetchall_hashref => { U =>[2,2,'$key_field'] },
  361. blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
  362. blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
  363. dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] },
  364. more_results => { U =>[1,1] },
  365. finish => { U =>[1,1] },
  366. cancel => { U =>[1,1], O=>0x0800 },
  367. rows => $keeperr,
  368. _get_fbav => undef,
  369. _set_fbav => { T=>6 },
  370. },
  371. );
  372. while ( my ($class, $meths) = each %DBI::DBI_methods ) {
  373. while ( my ($method, $info) = each %$meths ) {
  374. my $fullmeth = "DBI::${class}::$method";
  375. DBI->_install_method($fullmeth, 'DBI.pm', $info);
  376. }
  377. }
  378. {
  379. package DBI::common;
  380. @DBI::dr::ISA = ('DBI::common');
  381. @DBI::db::ISA = ('DBI::common');
  382. @DBI::st::ISA = ('DBI::common');
  383. }
  384. # End of init code
  385. END {
  386. return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
  387. local ($!,$?);
  388. DBI->trace_msg(" -- DBI::END\n", 2);
  389. # Let drivers know why we are calling disconnect_all:
  390. $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning
  391. DBI->disconnect_all() if %DBI::installed_drh;
  392. }
  393. sub CLONE {
  394. my $olddbis = $DBI::_dbistate;
  395. _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure
  396. DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n",
  397. $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate));
  398. while ( my ($driver, $drh) = each %DBI::installed_drh) {
  399. no strict 'refs';
  400. next if defined &{"DBD::${driver}::CLONE"};
  401. warn("$driver has no driver CLONE() function so is unsafe threaded\n");
  402. }
  403. %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize
  404. }
  405. sub parse_dsn {
  406. my ($class, $dsn) = @_;
  407. $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return;
  408. my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3);
  409. $driver ||= $ENV{DBI_DRIVER} || '';
  410. $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr;
  411. return ($scheme, $driver, $attr, $attr_hash, $dsn);
  412. }
  413. # --- The DBI->connect Front Door methods
  414. sub connect_cached {
  415. # For library code using connect_cached() with mod_perl
  416. # we redirect those calls to Apache::DBI::connect() as well
  417. my ($class, $dsn, $user, $pass, $attr) = @_;
  418. # XXX modifies callers data!
  419. ($attr ||= {})->{dbi_connect_method} =
  420. ($DBI::connect_via eq "Apache::DBI::connect")
  421. ? 'Apache::DBI::connect' : 'connect_cached';
  422. return $class->connect($dsn, $user, $pass, $attr);
  423. }
  424. sub connect {
  425. my $class = shift;
  426. my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
  427. my $driver;
  428. if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style
  429. Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions");
  430. ($old_driver, $attr) = ($attr, $old_driver);
  431. }
  432. my $connect_meth = $attr->{dbi_connect_method};
  433. $connect_meth ||= $DBI::connect_via; # fallback to default
  434. $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
  435. if ($DBI::dbi_debug) {
  436. local $^W = 0;
  437. pop @_ if $connect_meth ne 'connect';
  438. my @args = @_; $args[2] = '****'; # hide password
  439. DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
  440. }
  441. Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
  442. if (ref $old_driver or ($attr and not ref $attr) or ref $pass);
  443. # extract dbi:driver prefix from $dsn into $1
  444. $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
  445. or '' =~ /()/; # ensure $1 etc are empty if match fails
  446. my $driver_attrib_spec = $2 || '';
  447. # Set $driver. Old style driver, if specified, overrides new dsn style.
  448. $driver = $old_driver || $1 || $ENV{DBI_DRIVER}
  449. or Carp::croak("Can't connect to data source $dsn, no database driver specified "
  450. ."and DBI_DSN env var not set");
  451. if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') {
  452. my $dbi_autoproxy = $ENV{DBI_AUTOPROXY};
  453. my $proxy = 'Proxy';
  454. if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
  455. $proxy = $1;
  456. my $attr_spec = $2 || '';
  457. $driver_attrib_spec = ($driver_attrib_spec) ? "$driver_attrib_spec,$attr_spec" : $attr_spec;
  458. }
  459. $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn";
  460. $driver = $proxy;
  461. DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n");
  462. }
  463. my %attributes; # take a copy we can delete from
  464. if ($old_driver) {
  465. %attributes = %$attr if $attr;
  466. }
  467. else { # new-style connect so new default semantics
  468. %attributes = (
  469. PrintError => 1,
  470. AutoCommit => 1,
  471. ref $attr ? %$attr : (),
  472. # attributes in DSN take precedence over \%attr connect parameter
  473. $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (),
  474. );
  475. }
  476. $attr = \%attributes; # now set $attr to refer to our local copy
  477. my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver)
  478. or die "panic: $class->install_driver($driver) failed";
  479. # attributes in DSN take precedence over \%attr connect parameter
  480. $user = $attr->{Username} if defined $attr->{Username};
  481. $pass = delete $attr->{Password} if defined $attr->{Password};
  482. ($user, $pass) = $drh->default_user($user, $pass, $attr)
  483. if !(defined $user && defined $pass);
  484. $attr->{Username} = $user; # store username as attribute
  485. my $connect_closure = sub {
  486. my ($old_dbh, $override_attr) = @_;
  487. my $attr = {
  488. # copy so we can edit them each time we're called
  489. %attributes,
  490. # merge in modified attr in %$old_dbh, this should also copy in
  491. # the dbi_connect_closure attribute so we can reconnect again.
  492. %{ $override_attr || {} },
  493. };
  494. #warn "connect_closure: ".Data::Dumper::Dumper([\%attributes, $override_attr]);
  495. my $dbh;
  496. unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
  497. $user = '' if !defined $user;
  498. $dsn = '' if !defined $dsn;
  499. # $drh->errstr isn't safe here because $dbh->DESTROY may not have
  500. # been called yet and so the dbh errstr would not have been copied
  501. # up to the drh errstr. Certainly true for connect_cached!
  502. my $errstr = $DBI::errstr;
  503. $errstr = '(no error string)' if !defined $errstr;
  504. my $msg = "$class connect('$dsn','$user',...) failed: $errstr";
  505. DBI->trace_msg(" $msg\n");
  506. # XXX HandleWarn
  507. unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) {
  508. Carp::croak($msg) if $attr->{RaiseError};
  509. Carp::carp ($msg) if $attr->{PrintError};
  510. }
  511. $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
  512. return $dbh; # normally undef, but HandleError could change it
  513. }
  514. # handle basic RootClass subclassing:
  515. my $rebless_class = $attr->{RootClass} || ($class ne 'DBI' ? $class : '');
  516. if ($rebless_class) {
  517. no strict 'refs';
  518. if ($attr->{RootClass}) { # explicit attribute (rather than static call)
  519. delete $attr->{RootClass};
  520. DBI::_load_class($rebless_class, 0);
  521. }
  522. unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
  523. Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored");
  524. $rebless_class = undef;
  525. $class = 'DBI';
  526. }
  527. else {
  528. $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
  529. DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st'
  530. DBI::_rebless($dbh, $rebless_class); # appends '::db'
  531. }
  532. }
  533. if (%$attr) {
  534. DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, delete $attr->{DbTypeSubclass}, $attr)
  535. if $attr->{DbTypeSubclass};
  536. my $a;
  537. foreach $a (qw(RaiseError PrintError AutoCommit)) { # do these first
  538. next unless exists $attr->{$a};
  539. $dbh->{$a} = delete $attr->{$a};
  540. }
  541. foreach $a (keys %$attr) {
  542. eval { $dbh->{$a} = $attr->{$a} } or $@ && warn $@;
  543. }
  544. }
  545. # if we've been subclassed then let the subclass know that we're connected
  546. $dbh->connected($dsn, $user, $pass, $attr) if ref $dbh ne 'DBI::db';
  547. # if the caller has provided a callback then call it
  548. # especially useful with connect_cached() XXX not enabled/tested/documented
  549. if (0 and $dbh and my $oc = $dbh->{OnConnect}) { # XXX
  550. $oc->($dbh, $dsn, $user, $pass, $attr) if ref $oc eq 'CODE';
  551. }
  552. DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug;
  553. return $dbh;
  554. };
  555. my $dbh = &$connect_closure(undef, undef);
  556. $dbh->{dbi_connect_closure} = $connect_closure if $dbh;
  557. return $dbh;
  558. }
  559. sub disconnect_all {
  560. keys %DBI::installed_drh; # reset iterator
  561. while ( my ($name, $drh) = each %DBI::installed_drh ) {
  562. $drh->disconnect_all() if ref $drh;
  563. }
  564. }
  565. sub disconnect { # a regular beginners bug
  566. Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)");
  567. }
  568. sub install_driver { # croaks on failure
  569. my $class = shift;
  570. my($driver, $attr) = @_;
  571. my $drh;
  572. $driver ||= $ENV{DBI_DRIVER} || '';
  573. # allow driver to be specified as a 'dbi:driver:' string
  574. $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
  575. Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
  576. unless ($driver and @_<=3);
  577. # already installed
  578. return $drh if $drh = $DBI::installed_drh{$driver};
  579. $class->trace_msg(" -> $class->install_driver($driver"
  580. .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n")
  581. if $DBI::dbi_debug;
  582. # --- load the code
  583. my $driver_class = "DBD::$driver";
  584. eval qq{package # hide from PAUSE
  585. DBI::_firesafe; # just in case
  586. require $driver_class; # load the driver
  587. };
  588. if ($@) {
  589. my $err = $@;
  590. my $advice = "";
  591. if ($err =~ /Can't find loadable object/) {
  592. $advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
  593. ."\nIn which case you need to use that new perl binary."
  594. ."\nOr perhaps only the .pm file was installed but not the shared object file."
  595. }
  596. elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
  597. my @drv = $class->available_drivers(1);
  598. $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
  599. ."or perhaps the capitalisation of '$driver' isn't right.\n"
  600. ."Available drivers: ".join(", ", @drv).".";
  601. }
  602. elsif ($err =~ /Can't load .*? for module DBD::/) {
  603. $advice = "Perhaps a required shared library or dll isn't installed where expected";
  604. }
  605. elsif ($err =~ /Can't locate .*? in \@INC/) {
  606. $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
  607. }
  608. Carp::croak("install_driver($driver) failed: $err$advice\n");
  609. }
  610. if ($DBI::dbi_debug) {
  611. no strict 'refs';
  612. (my $driver_file = $driver_class) =~ s/::/\//g;
  613. my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
  614. $class->trace_msg(" install_driver: $driver_class version $dbd_ver"
  615. ." loaded from $INC{qq($driver_file.pm)}\n");
  616. }
  617. # --- do some behind-the-scenes checks and setups on the driver
  618. $class->setup_driver($driver_class);
  619. # --- run the driver function
  620. $drh = eval { $driver_class->driver($attr || {}) };
  621. unless ($drh && ref $drh && !$@) {
  622. my $advice = "";
  623. # catch people on case in-sensitive systems using the wrong case
  624. $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
  625. if $@ =~ /locate object method/;
  626. Carp::croak("$driver_class initialisation failed: $@$advice");
  627. }
  628. $DBI::installed_drh{$driver} = $drh;
  629. $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug;
  630. $drh;
  631. }
  632. *driver = \&install_driver; # currently an alias, may change
  633. sub setup_driver {
  634. my ($class, $driver_class) = @_;
  635. my $type;
  636. foreach $type (qw(dr db st)){
  637. my $class = $driver_class."::$type";
  638. no strict 'refs';
  639. push @{"${class}::ISA"}, "DBD::_::$type"
  640. unless UNIVERSAL::isa($class, "DBD::_::$type");
  641. my $mem_class = "DBD::_mem::$type";
  642. push @{"${class}_mem::ISA"}, $mem_class
  643. unless UNIVERSAL::isa("${class}_mem", $mem_class)
  644. or $DBI::PurePerl;
  645. }
  646. }
  647. sub _rebless {
  648. my $dbh = shift;
  649. my ($outer, $inner) = DBI::_handles($dbh);
  650. my $class = shift(@_).'::db';
  651. bless $inner => $class;
  652. bless $outer => $class; # outer last for return
  653. }
  654. sub _set_isa {
  655. my ($classes, $topclass) = @_;
  656. my $trace = DBI->trace_msg(" _set_isa([@$classes])\n");
  657. foreach my $suffix ('::db','::st') {
  658. my $previous = $topclass || 'DBI'; # trees are rooted here
  659. foreach my $class (@$classes) {
  660. my $base_class = $previous.$suffix;
  661. my $sub_class = $class.$suffix;
  662. my $sub_class_isa = "${sub_class}::ISA";
  663. no strict 'refs';
  664. if (@$sub_class_isa) {
  665. DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n")
  666. if $trace;
  667. }
  668. else {
  669. @$sub_class_isa = ($base_class) unless @$sub_class_isa;
  670. DBI->trace_msg(" $sub_class_isa = $base_class\n")
  671. if $trace;
  672. }
  673. $previous = $class;
  674. }
  675. }
  676. }
  677. sub _rebless_dbtype_subclass {
  678. my ($dbh, $rootclass, $DbTypeSubclass, $attr) = @_;
  679. # determine the db type names for class hierarchy
  680. my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass, $attr);
  681. # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc)
  682. $_ = $rootclass.'::'.$_ foreach (@hierarchy);
  683. # load the modules from the 'top down'
  684. DBI::_load_class($_, 1) foreach (reverse @hierarchy);
  685. # setup class hierarchy if needed, does both '::db' and '::st'
  686. DBI::_set_isa(\@hierarchy, $rootclass);
  687. # finally bless the handle into the subclass
  688. DBI::_rebless($dbh, $hierarchy[0]);
  689. }
  690. sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC
  691. my ($dbh, $DbTypeSubclass, $attr) = @_;
  692. if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') {
  693. # treat $DbTypeSubclass as a comma separated list of names
  694. my @dbtypes = split /\s*,\s*/, $DbTypeSubclass;
  695. $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n");
  696. return @dbtypes;
  697. }
  698. # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future?
  699. my $driver = $dbh->{Driver}->{Name};
  700. if ( $driver eq 'Proxy' ) {
  701. # XXX Looking into the internals of DBD::Proxy is questionable!
  702. ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i
  703. or die "Can't determine driver name from proxy";
  704. }
  705. my @dbtypes = (ucfirst($driver));
  706. if ($driver eq 'ODBC' || $driver eq 'ADO') {
  707. # XXX will move these out and make extensible later:
  708. my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar'
  709. my %_dbtype_name_map = (
  710. 'Microsoft SQL Server' => 'MSSQL',
  711. 'SQL Server' => 'Sybase',
  712. 'Adaptive Server Anywhere' => 'ASAny',
  713. 'ADABAS D' => 'AdabasD',
  714. );
  715. my $name;
  716. $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME
  717. if $driver eq 'ODBC';
  718. $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value
  719. if $driver eq 'ADO';
  720. die "Can't determine driver name! ($DBI::errstr)\n"
  721. unless $name;
  722. my $dbtype;
  723. if ($_dbtype_name_map{$name}) {
  724. $dbtype = $_dbtype_name_map{$name};
  725. }
  726. else {
  727. if ($name =~ /($_dbtype_name_regexp)/) {
  728. $dbtype = lc($1);
  729. }
  730. else { # generic mangling for other names:
  731. $dbtype = lc($name);
  732. }
  733. $dbtype =~ s/\b(\w)/\U$1/g;
  734. $dbtype =~ s/\W+/_/g;
  735. }
  736. # add ODBC 'behind' ADO
  737. push @dbtypes, 'ODBC' if $driver eq 'ADO';
  738. # add discovered dbtype in front of ADO/ODBC
  739. unshift @dbtypes, $dbtype;
  740. }
  741. @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes)
  742. if (ref $DbTypeSubclass eq 'CODE');
  743. $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n");
  744. return @dbtypes;
  745. }
  746. sub _load_class {
  747. my ($load_class, $missing_ok) = @_;
  748. DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2);
  749. no strict 'refs';
  750. return 1 if @{"$load_class\::ISA"}; # already loaded/exists
  751. (my $module = $load_class) =~ s!::!/!g;
  752. DBI->trace_msg(" _load_class require $module\n", 2);
  753. eval { require "$module.pm"; };
  754. return 1 unless $@;
  755. return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
  756. die $@;
  757. }
  758. sub init_rootclass { # deprecated
  759. return 1;
  760. }
  761. *internal = \&DBD::Switch::dr::driver;
  762. sub available_drivers {
  763. my($quiet) = @_;
  764. my(@drivers, $d, $f);
  765. local(*DBI::DIR, $@);
  766. my(%seen_dir, %seen_dbd);
  767. my $haveFileSpec = eval { require File::Spec };
  768. foreach $d (@INC){
  769. chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
  770. my $dbd_dir =
  771. ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
  772. next unless -d $dbd_dir;
  773. next if $seen_dir{$d};
  774. $seen_dir{$d} = 1;
  775. # XXX we have a problem here with case insensitive file systems
  776. # XXX since we can't tell what case must be used when loading.
  777. opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
  778. foreach $f (readdir(DBI::DIR)){
  779. next unless $f =~ s/\.pm$//;
  780. next if $f eq 'NullP';
  781. if ($seen_dbd{$f}){
  782. Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
  783. unless $quiet;
  784. } else {
  785. push(@drivers, $f);
  786. }
  787. $seen_dbd{$f} = $d;
  788. }
  789. closedir(DBI::DIR);
  790. }
  791. # "return sort @drivers" will not DWIM in scalar context.
  792. return wantarray ? sort @drivers : @drivers;
  793. }
  794. sub installed_versions {
  795. my ($class, $quiet) = @_;
  796. my %error;
  797. my %version = ( DBI => $DBI::VERSION );
  798. $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION
  799. if $DBI::PurePerl;
  800. for my $driver ($class->available_drivers($quiet)) {
  801. next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC;
  802. my $drh = eval {
  803. local $SIG{__WARN__} = sub {};
  804. $class->install_driver($driver);
  805. };
  806. ($error{"DBD::$driver"}=$@),next if $@;
  807. no strict 'refs';
  808. my $vers = ${"DBD::$driver" . '::VERSION'};
  809. $version{"DBD::$driver"} = $vers || '?';
  810. }
  811. if (wantarray) {
  812. return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version;
  813. }
  814. if (!defined wantarray) { # void context
  815. require Config; # add more detail
  816. $version{OS} = "$^O\t($Config::Config{osvers})";
  817. $version{Perl} = "$]\t($Config::Config{archname})";
  818. $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_})
  819. for keys %error;
  820. printf " %-16s: %s\n",$_,$version{$_}
  821. for reverse sort keys %version;
  822. }
  823. return \%version;
  824. }
  825. sub data_sources {
  826. my ($class, $driver, @other) = @_;
  827. my $drh = $class->install_driver($driver);
  828. my @ds = $drh->data_sources(@other);
  829. return @ds;
  830. }
  831. sub neat_list {
  832. my ($listref, $maxlen, $sep) = @_;
  833. $maxlen = 0 unless defined $maxlen; # 0 == use internal default
  834. $sep = ", " unless defined $sep;
  835. join($sep, map { neat($_,$maxlen) } @$listref);
  836. }
  837. sub dump_results { # also aliased as a method in DBD::_::st
  838. my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
  839. return 0 unless $sth;
  840. $maxlen ||= 35;
  841. $lsep ||= "\n";
  842. $fh ||= \*STDOUT;
  843. my $rows = 0;
  844. my $ref;
  845. while($ref = $sth->fetch) {
  846. print $fh $lsep if $rows++ and $lsep;
  847. my $str = neat_list($ref,$maxlen,$fsep);
  848. print $fh $str; # done on two lines to avoid 5.003 errors
  849. }
  850. print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
  851. $rows;
  852. }
  853. sub data_diff {
  854. my ($a, $b, $logical) = @_;
  855. my $diff = data_string_diff($a, $b);
  856. return "" if $logical and !$diff;
  857. my $a_desc = data_string_desc($a);
  858. my $b_desc = data_string_desc($b);
  859. return "" if !$diff and $a_desc eq $b_desc;
  860. $diff ||= "Strings contain the same sequence of characters"
  861. if length($a);
  862. $diff .= "\n" if $diff;
  863. return "a: $a_desc\nb: $b_desc\n$diff";
  864. }
  865. sub data_string_diff {
  866. # Compares 'logical' characters, not bytes, so a latin1 string and an
  867. # an equivalent unicode string will compare as equal even though their
  868. # byte encodings are different.
  869. my ($a, $b) = @_;
  870. unless (defined $a and defined $b) { # one undef
  871. return ""
  872. if !defined $a and !defined $b;
  873. return "String a is undef, string b has ".length($b)." characters"
  874. if !defined $a;
  875. return "String b is undef, string a has ".length($a)." characters"
  876. if !defined $b;
  877. }
  878. require utf8;
  879. # hack to cater for perl 5.6
  880. *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  881. my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a);
  882. my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b);
  883. my $i = 0;
  884. while (@a_chars && @b_chars) {
  885. ++$i, shift(@a_chars), shift(@b_chars), next
  886. if $a_chars[0] == $b_chars[0];# compare ordinal values
  887. my @desc = map {
  888. $_ > 255 ? # if wide character...
  889. sprintf("\\x{%04X}", $_) : # \x{...}
  890. chr($_) =~ /[[:cntrl:]]/ ? # else if control character ...
  891. sprintf("\\x%02X", $_) : # \x..
  892. chr($_) # else as themselves
  893. } ($a_chars[0], $b_chars[0]);
  894. # highlight probable double-encoding?
  895. foreach my $c ( @desc ) {
  896. next unless $c =~ m/\\x\{08(..)}/;
  897. $c .= "='" .chr(hex($1)) ."'"
  898. }
  899. return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]";
  900. }
  901. return "String a truncated after $i characters" if @b_chars;
  902. return "String b truncated after $i characters" if @a_chars;
  903. return "";
  904. }
  905. sub data_string_desc { # describe a data string
  906. my ($a) = @_;
  907. require bytes;
  908. require utf8;
  909. # hacks to cater for perl 5.6
  910. *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  911. *utf8::valid = sub { 1 } unless defined &utf8::valid;
  912. # Give sufficient info to help diagnose at least these kinds of situations:
  913. # - valid UTF8 byte sequence but UTF8 flag not set
  914. # (might be ascii so also need to check for hibit to make it worthwhile)
  915. # - UTF8 flag set but invalid UTF8 byte sequence
  916. # could do better here, but this'll do for now
  917. my $utf8 = sprintf "UTF8 %s%s",
  918. utf8::is_utf8($a) ? "on" : "off",
  919. utf8::valid($a||'') ? "" : " but INVALID encoding";
  920. return "$utf8, undef" unless defined $a;
  921. my $is_ascii = $a =~ m/^[\000-\177]*$/;
  922. return sprintf "%s, %s, %d characters %d bytes",
  923. $utf8, $is_ascii ? "ASCII" : "non-ASCII",
  924. length($a), bytes::length($a);
  925. }
  926. sub connect_test_perf {
  927. my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
  928. Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
  929. # these are non standard attributes just for this special method
  930. my $loops ||= $attr->{dbi_loops} || 5;
  931. my $par ||= $attr->{dbi_par} || 1; # parallelism
  932. my $verb ||= $attr->{dbi_verb} || 1;
  933. print "$dsn: testing $loops sets of $par connections:\n";
  934. require Benchmark;
  935. require "FileHandle.pm"; # don't let toke.c create empty FileHandle package
  936. $| = 1;
  937. my $t0 = new Benchmark; # not currently used
  938. my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
  939. my $t1 = new Benchmark;
  940. my $loop;
  941. for $loop (1..$loops) {
  942. my @cons;
  943. print "Connecting... " if $verb;
  944. for (1..$par) {
  945. print "$_ ";
  946. push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
  947. or Carp::croak("Can't connect # $_: $DBI::errstr\n"));
  948. }
  949. print "\nDisconnecting...\n" if $verb;
  950. for (@cons) {
  951. $_->disconnect or warn "bad disconnect $DBI::errstr"
  952. }
  953. }
  954. my $t2 = new Benchmark;
  955. my $td = Benchmark::timediff($t2, $t1);
  956. printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td);
  957. print "\n";
  958. return $td;
  959. }
  960. # Help people doing DBI->errstr, might even document it one day
  961. # XXX probably best moved to cheaper XS code
  962. sub err { $DBI::err }
  963. sub errstr { $DBI::errstr }
  964. # --- Private Internal Function for Creating New DBI Handles
  965. sub _new_handle {
  966. my ($class, $parent, $attr, $imp_data, $imp_class) = @_;
  967. Carp::croak('Usage: DBI::_new_handle'
  968. .'($class_name, parent_handle, \%attr, $imp_data)'."\n"
  969. .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n")
  970. unless (@_ == 5 and (!$parent or ref $parent)
  971. and ref $attr eq 'HASH'
  972. and $imp_class);
  973. $attr->{ImplementorClass} = $imp_class
  974. or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given");
  975. DBI->trace_msg(" New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n")
  976. if $DBI::dbi_debug >= 3;
  977. # This is how we create a DBI style Object:
  978. my (%hash, $i, $h);
  979. $i = tie %hash, $class, $attr; # ref to inner hash (for driver)
  980. $h = bless \%hash, $class; # ref to outer hash (for application)
  981. # The above tie and bless may migrate down into _setup_handle()...
  982. # Now add magic so DBI method dispatch works
  983. DBI::_setup_handle($h, $imp_class, $parent, $imp_data);
  984. return $h unless wantarray;
  985. ($h, $i);
  986. }
  987. # XXX minimum constructors for the tie's (alias to XS version)
  988. sub DBI::st::TIEHASH { bless $_[1] => $_[0] };
  989. *DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
  990. *DBI::db::TIEHASH = \&DBI::st::TIEHASH;
  991. # These three special constructors are called by the drivers
  992. # The way they are called is likely to change.
  993. my $profile;
  994. sub _new_drh { # called by DBD::<drivername>::driver()
  995. my ($class, $initial_attr, $imp_data) = @_;
  996. # Provide default storage for State,Err and Errstr.
  997. # Note that these are shared by all child handles by default! XXX
  998. # State must be undef to get automatic faking in DBI::var::FETCH
  999. my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
  1000. my $attr = {
  1001. # these attributes get copied down to child handles by default
  1002. 'State' => \$h_state_store, # Holder for DBI::state
  1003. 'Err' => \$h_err_store, # Holder for DBI::err
  1004. 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr
  1005. 'TraceLevel' => 0,
  1006. FetchHashKeyName=> 'NAME',
  1007. %$initial_attr,
  1008. };
  1009. my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class);
  1010. # XXX DBI_PROFILE unless DBI::PurePerl because for some reason
  1011. # it kills the t/zz_*_pp.t tests (they silently exit early)
  1012. if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) {
  1013. # The profile object created here when the first driver is loaded
  1014. # is shared by all drivers so we end up with just one set of profile
  1015. # data and thus the 'total time in DBI' is really the true total.
  1016. if (!$profile) { # first time
  1017. $h->{Profile} = $ENV{DBI_PROFILE};
  1018. $profile = $h->{Profile};
  1019. }
  1020. else {
  1021. $h->{Profile} = $profile;
  1022. }
  1023. }
  1024. return $h unless wantarray;
  1025. ($h, $i);
  1026. }
  1027. sub _new_dbh { # called by DBD::<drivername>::dr::connect()
  1028. my ($drh, $attr, $imp_data) = @_;
  1029. my $imp_class = $drh->{ImplementorClass}
  1030. or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
  1031. substr($imp_class,-4,4) = '::db';
  1032. my $app_class = ref $drh;
  1033. substr($app_class,-4,4) = '::db';
  1034. $attr->{Err} ||= \my $err;
  1035. $attr->{Errstr} ||= \my $errstr;
  1036. $attr->{State} ||= \my $state;
  1037. _new_handle($app_class, $drh, $attr, $imp_data, $imp_class);
  1038. }
  1039. sub _new_sth { # called by DBD::<drivername>::db::prepare)
  1040. my ($dbh, $attr, $imp_data) = @_;
  1041. my $imp_class = $dbh->{ImplementorClass}
  1042. or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
  1043. substr($imp_class,-4,4) = '::st';
  1044. my $app_class = ref $dbh;
  1045. substr($app_class,-4,4) = '::st';
  1046. _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class);
  1047. }
  1048. # end of DBI package
  1049. # --------------------------------------------------------------------
  1050. # === The internal DBI Switch pseudo 'driver' class ===
  1051. { package # hide from PAUSE
  1052. DBD::Switch::dr;
  1053. DBI->setup_driver('DBD::Switch'); # sets up @ISA
  1054. $DBD::Switch::dr::imp_data_size = 0;
  1055. $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning
  1056. my $drh;
  1057. sub driver {
  1058. return $drh if $drh; # a package global
  1059. my $inner;
  1060. ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
  1061. 'Name' => 'Switch',
  1062. 'Version' => $DBI::VERSION,
  1063. 'Attribution' => "DBI $DBI::VERSION by Tim Bunce",
  1064. });
  1065. Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
  1066. return $drh;
  1067. }
  1068. sub CLONE {
  1069. undef $drh;
  1070. }
  1071. sub FETCH {
  1072. my($drh, $key) = @_;
  1073. return DBI->trace if $key eq 'DebugDispatch';
  1074. return undef if $key eq 'DebugLog'; # not worth fetching, sorry
  1075. return $drh->DBD::_::dr::FETCH($key);
  1076. undef;
  1077. }
  1078. sub STORE {
  1079. my($drh, $key, $value) = @_;
  1080. if ($key eq 'DebugDispatch') {
  1081. DBI->trace($value);
  1082. } elsif ($key eq 'DebugLog') {
  1083. DBI->trace(-1, $value);
  1084. } else {
  1085. $drh->DBD::_::dr::STORE($key, $value);
  1086. }
  1087. }
  1088. }
  1089. # --------------------------------------------------------------------
  1090. # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
  1091. # We only define default methods for harmless functions.
  1092. # We don't, for example, define a DBD::_::st::prepare()
  1093. { package # hide from PAUSE
  1094. DBD::_::common; # ====== Common base class methods ======
  1095. use strict;
  1096. # methods common to all handle types:
  1097. sub _not_impl {
  1098. my ($h, $method) = @_;
  1099. $h->trace_msg("Driver does not implement the $method method.\n");
  1100. return; # empty list / undef
  1101. }
  1102. # generic TIEHASH default methods:
  1103. sub FIRSTKEY { }
  1104. sub NEXTKEY { }
  1105. sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef?
  1106. sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" }
  1107. *dump_handle = \&DBI::dump_handle;
  1108. sub install_method {
  1109. # special class method called directly by apps and/or drivers
  1110. # to install new methods into the DBI dispatcher
  1111. # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' });
  1112. my ($class, $method, $attr) = @_;
  1113. Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st")
  1114. unless $class =~ /^DBD::(\w+)::(dr|db|st)$/;
  1115. my ($driver, $subtype) = ($1, $2);
  1116. Carp::croak("invalid method name '$method'")
  1117. unless $method =~ m/^([a-z]+_)\w+$/;
  1118. my $prefix = $1;
  1119. my $reg_info = $dbd_prefix_registry->{$prefix};
  1120. Carp::croak("method name prefix '$prefix' is not registered") unless $reg_info;
  1121. my %attr = %{$attr||{}}; # copy so we can edit
  1122. # XXX reformat $attr as needed for _install_method
  1123. my ($caller_pkg, $filename, $line) = caller;
  1124. DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr);
  1125. }
  1126. sub parse_trace_flags {
  1127. my ($h, $spec) = @_;
  1128. my $level = 0;
  1129. my $flags = 0;
  1130. my @unknown;
  1131. for my $word (split /\s*[|&,]\s*/, $spec) {
  1132. if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) {
  1133. $level = $word;
  1134. } elsif ($word eq 'ALL') {
  1135. $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches
  1136. last;
  1137. } elsif (my $flag = $h->parse_trace_flag($word)) {
  1138. $flags |= $flag;
  1139. }
  1140. else {
  1141. push @unknown, $word;
  1142. }
  1143. }
  1144. if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) {
  1145. Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ".
  1146. join(" ", map { DBI::neat($_) } @unknown));
  1147. }
  1148. $flags |= $level;
  1149. return $flags;
  1150. }
  1151. sub parse_trace_flag {
  1152. my ($h, $name) = @_;
  1153. # 0xddDDDDrL (driver, DBI, reserved, Level)
  1154. return 0x00000100 if $name eq 'SQL';
  1155. return;
  1156. }
  1157. }
  1158. { package # hide from PAUSE
  1159. DBD::_::dr; # ====== DRIVER ======
  1160. @DBD::_::dr::ISA = qw(DBD::_::common);
  1161. use strict;
  1162. sub default_user {
  1163. my ($drh, $user, $pass, $attr) = @_;
  1164. $user = $ENV{DBI_USER} unless defined $user;
  1165. $pass = $ENV{DBI_PASS} unless defined $pass;
  1166. return ($user, $pass);
  1167. }
  1168. sub connect { # normally overridden, but a handy default
  1169. my ($drh, $dsn, $user, $auth) = @_;
  1170. my ($this) = DBI::_new_dbh($drh, {
  1171. 'Name' => $dsn,
  1172. });
  1173. # XXX debatable as there's no "server side" here
  1174. # (and now many uses would trigger warnings on DESTROY)
  1175. # $this->STORE(Active => 1);
  1176. $this;
  1177. }
  1178. sub connect_cached {
  1179. my $drh = shift;
  1180. my ($dsn, $user, $auth, $attr)= @_;
  1181. # Needs support at dbh level to clear cache before complaining about
  1182. # active children. The XS template code does this. Drivers not using
  1183. # the template must handle clearing the cache themselves.
  1184. my $cache = $drh->FETCH('CachedKids');
  1185. $drh->STORE('CachedKids', $cache = {}) unless $cache;
  1186. my @attr_keys = $attr ? sort keys %$attr : ();
  1187. my $key = do { local $^W; # silence undef warnings
  1188. join "~~", $dsn, $user||'', $auth||'', $attr ? (@attr_keys,@{$attr}{@attr_keys}) : ()
  1189. };
  1190. my $dbh = $cache->{$key};
  1191. if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) {
  1192. # XXX warn if BegunWork?
  1193. # XXX warn if $dbh->FETCH('AutoCommit') != $attr->{AutoCommit} ?
  1194. # but that's just one (bad) case of a more general issue.
  1195. return $dbh;
  1196. }
  1197. $dbh = $drh->connect(@_);
  1198. $cache->{$key} = $dbh; # replace prev entry, even if connect failed
  1199. return $dbh;
  1200. }
  1201. }
  1202. { package # hide from PAUSE
  1203. DBD::_::db; # ====== DATABASE ======
  1204. @DBD::_::db::ISA = qw(DBD::_::common);
  1205. use strict;
  1206. sub clone {
  1207. my ($old_dbh, $attr) = @_;
  1208. my $closure = $old_dbh->{dbi_connect_closure} or return;
  1209. unless ($attr) {
  1210. # copy attributes visible in the attribute cache
  1211. keys %$old_dbh; # reset iterator
  1212. while ( my ($k, $v) = each %$old_dbh ) {
  1213. # ignore non-code refs, i.e., caches, handles, Err etc
  1214. next if ref $v && ref $v ne 'CODE'; # HandleError etc
  1215. $attr->{$k} = $v;
  1216. }
  1217. # explicitly set attributes which are unlikely to be in the
  1218. # attribute cache, i.e., boolean's and some others
  1219. $attr->{$_} = $old_dbh->FETCH($_) for (qw(
  1220. AutoCommit ChopBlanks InactiveDestroy
  1221. LongTruncOk PrintError PrintWarn Profile RaiseError
  1222. ShowErrorStatement TaintIn TaintOut
  1223. ));
  1224. }
  1225. # use Data::Dumper; warn Dumper([$old_dbh, $attr]);
  1226. my $new_dbh = &$closure($old_dbh, $attr);
  1227. unless ($new_dbh) {
  1228. # need to copy err/errstr from driver back into $old_dbh
  1229. my $drh = $old_dbh->{Driver};
  1230. return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state);
  1231. }
  1232. return $new_dbh;
  1233. }
  1234. sub quote_identifier {
  1235. my ($dbh, @id) = @_;
  1236. my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
  1237. my $info = $dbh->{dbi_quote_identifier_cache} ||= [
  1238. $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR
  1239. $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR
  1240. $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION
  1241. ];
  1242. my $quote = $info->[0];
  1243. foreach (@id) { # quote the elements
  1244. next unless defined;
  1245. s/$quote/$quote$quote/g; # escape embedded quotes
  1246. $_ = qq{$quote$_$quote};
  1247. }
  1248. # strip out catalog if present for special handling
  1249. my $catalog = (@id >= 3) ? shift @id : undef;
  1250. # join the dots, ignoring any null/undef elements (ie schema)
  1251. my $quoted_id = join '.', grep { defined } @id;
  1252. if ($catalog) { # add catalog correctly
  1253. $quoted_id = ($info->[2] == 2) # SQL_CL_END
  1254. ? $quoted_id . $info->[1] . $catalog
  1255. : $catalog . $info->[1] . $quoted_id;
  1256. }
  1257. return $quoted_id;
  1258. }
  1259. sub quote {
  1260. my ($dbh, $str, $data_type) = @_;
  1261. return "NULL" unless defined $str;
  1262. unless ($data_type) {
  1263. $str =~ s/'/''/g; # ISO SQL2
  1264. return "'$str'";
  1265. }
  1266. my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
  1267. my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
  1268. my $lp = $prefixes->{$data_type};
  1269. my $ls = $suffixes->{$data_type};
  1270. if ( ! defined $lp || ! defined $ls ) {
  1271. my $ti = $dbh->type_info($data_type);
  1272. $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
  1273. $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
  1274. }
  1275. return $str unless $lp || $ls; # no quoting required
  1276. # XXX don't know what the standard says about escaping
  1277. # in the 'general case' (where $lp != "'").
  1278. # So we just do this and hope:
  1279. $str =~ s/$lp/$lp$lp/g
  1280. if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
  1281. return "$lp$str$ls";
  1282. }
  1283. sub rows { -1 } # here so $DBI::rows 'works' after using $dbh
  1284. sub do {
  1285. my($dbh, $statement, $attr, @params) = @_;
  1286. my $sth = $dbh->prepare($statement, $attr) or return undef;
  1287. $sth->execute(@params) or return undef;
  1288. my $rows = $sth->rows;
  1289. ($rows == 0) ? "0E0" : $rows;
  1290. }
  1291. sub _do_selectrow {
  1292. my ($method, $dbh, $stmt, $attr, @bind) = @_;
  1293. my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr))
  1294. or return;
  1295. $sth->execute(@bind)
  1296. or return;
  1297. my $row = $sth->$method()
  1298. and $sth->finish;
  1299. return $row;
  1300. }
  1301. sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
  1302. # XXX selectrow_array/ref also have C implementations in Driver.xst
  1303. sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
  1304. sub selectrow_array {
  1305. my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
  1306. return $row->[0] unless wantarray;
  1307. return @$row;
  1308. }
  1309. # XXX selectall_arrayref also has C implementation in Driver.xst
  1310. # which fallsback to this if a slice is given
  1311. sub selectall_arrayref {
  1312. my ($dbh, $stmt, $attr, @bind) = @_;
  1313. my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)
  1314. or return;
  1315. $sth->execute(@bind) || return;
  1316. my $slice = $attr->{Slice}; # typically undef, else hash or array ref
  1317. if (!$slice and $slice=$attr->{Columns}) {
  1318. if (ref $slice eq 'ARRAY') { # map col idx to perl array idx
  1319. $slice = [ @{$attr->{Columns}} ]; # take a copy
  1320. for (@$slice) { $_-- }
  1321. }
  1322. }
  1323. my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows});
  1324. $sth->finish if defined $MaxRows;
  1325. return $rows;
  1326. }
  1327. sub selectall_hashref {
  1328. my ($dbh, $stmt, $key_field, $attr, @bind) = @_;
  1329. my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
  1330. return unless $sth;
  1331. $sth->execute(@bind) || return;
  1332. return $sth->fetchall_hashref($key_field);
  1333. }
  1334. sub selectcol_arrayref {
  1335. my ($dbh, $stmt, $attr, @bind) = @_;
  1336. my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
  1337. return unless $sth;
  1338. $sth->execute(@bind) || return;
  1339. my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
  1340. my @values = (undef) x @columns;
  1341. my $idx = 0;
  1342. for (@columns) {
  1343. $sth->bind_col($_, \$values[$idx++]) || return;
  1344. }
  1345. my @col;
  1346. if (my $max = $attr->{MaxRows}) {
  1347. push @col, @values while @col<$max && $sth->fetch;
  1348. }
  1349. else {
  1350. push @col, @values while $sth->fetch;
  1351. }
  1352. return \@col;
  1353. }
  1354. sub prepare_cached {
  1355. my ($dbh, $statement, $attr, $if_active) = @_;
  1356. # Needs support at dbh level to clear cache before complaining about
  1357. # active children. The XS template code does this. Drivers not using
  1358. # the template must handle clearing the cache themselves.
  1359. my $cache = $dbh->FETCH('CachedKids');
  1360. $dbh->STORE('CachedKids', $cache = {}) unless $cache;
  1361. my @attr_keys = ($attr) ? sort keys %$attr : ();
  1362. my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement;
  1363. my $sth = $cache->{$key};
  1364. if ($sth) {
  1365. return $sth unless $sth->FETCH('Active');
  1366. Carp::carp("prepare_cached($statement) statement handle $sth still Active")
  1367. unless ($if_active ||= 0);
  1368. $sth->finish if $if_active <= 1;
  1369. return $sth if $if_active <= 2;
  1370. }
  1371. $sth = $dbh->prepare($statement, $attr);
  1372. $cache->{$key} = $sth if $sth;
  1373. return $sth;
  1374. }
  1375. sub ping {
  1376. shift->_not_impl('ping');
  1377. "0 but true"; # special kind of true 0
  1378. }
  1379. sub begin_work {
  1380. my $dbh = shift;
  1381. return $dbh->set_err(1, "Already in a transaction")
  1382. unless $dbh->FETCH('AutoCommit');
  1383. $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it
  1384. $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action
  1385. return 1;
  1386. }
  1387. sub primary_key {
  1388. my ($dbh, @args) = @_;
  1389. my $sth = $dbh->primary_key_info(@args) or return;
  1390. my ($row, @col);
  1391. push @col, $row->[3] while ($row = $sth->fetch);
  1392. Carp::croak("primary_key method not called in list context")
  1393. unless wantarray; # leave us some elbow room
  1394. return @col;
  1395. }
  1396. sub tables {
  1397. my ($dbh, @args) = @_;
  1398. my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return;
  1399. my $tables = $sth->fetchall_arrayref or return;
  1400. my @tables;
  1401. if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR
  1402. @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables;
  1403. }
  1404. else { # temporary old style hack (yeach)
  1405. @tables = map {
  1406. my $name = $_->[2];
  1407. if ($_->[1]) {
  1408. my $schema = $_->[1];
  1409. # a sad hack (mostly for Informix I recall)
  1410. my $quote = ($schema eq uc($schema)) ? '' : '"';
  1411. $name = "$quote$schema$quote.$name"
  1412. }
  1413. $name;
  1414. } @$tables;
  1415. }
  1416. return @tables;
  1417. }
  1418. sub type_info { # this should be sufficient for all drivers
  1419. my ($dbh, $data_type) = @_;
  1420. my $idx_hash;
  1421. my $tia = $dbh->{dbi_type_info_row_cache};
  1422. if ($tia) {
  1423. $idx_hash = $dbh->{dbi_type_info_idx_cache};
  1424. }
  1425. else {
  1426. my $temp = $dbh->type_info_all;
  1427. return unless $temp && @$temp;
  1428. # we cache here because type_info_all may be expensive to call
  1429. $tia = $dbh->{dbi_type_info_row_cache} = $temp;
  1430. $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
  1431. }
  1432. my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
  1433. Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
  1434. if $dt_idx && $dt_idx != 1;
  1435. # --- simple DATA_TYPE match filter
  1436. my @ti;
  1437. my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
  1438. foreach $data_type (@data_type_list) {
  1439. if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
  1440. push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
  1441. }
  1442. else { # SQL_ALL_TYPES
  1443. push @ti, @$tia;
  1444. }
  1445. last if @ti; # found at least one match
  1446. }
  1447. # --- format results into list of hash refs
  1448. my $idx_fields = keys %$idx_hash;
  1449. my @idx_names = map { uc($_) } keys %$idx_hash;
  1450. my @idx_values = values %$idx_hash;
  1451. Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
  1452. if @ti && @{$ti[0]} != $idx_fields;
  1453. my @out = map {
  1454. my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
  1455. } @ti;
  1456. return $out[0] unless wantarray;
  1457. return @out;
  1458. }
  1459. sub data_sources {
  1460. my ($dbh, @other) = @_;
  1461. my $drh = $dbh->{Driver}; # XXX proxy issues?
  1462. return $drh->data_sources(@other);
  1463. }
  1464. }
  1465. { package # hide from PAUSE
  1466. DBD::_::st; # ====== STATEMENT ======
  1467. @DBD::_::st::ISA = qw(DBD::_::common);
  1468. use strict;
  1469. sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
  1470. #
  1471. # ********************************************************
  1472. #
  1473. # BEGIN ARRAY BINDING
  1474. #
  1475. # Array binding support for drivers which don't support
  1476. # array binding, but have sufficient interfaces to fake it.
  1477. # NOTE: mixing scalars and arrayrefs requires using bind_param_array
  1478. # for *all* params...unless we modify bind_param for the default
  1479. # case...
  1480. #
  1481. # 2002-Apr-10 D. Arnold
  1482. sub bind_param_array {
  1483. my $sth = shift;
  1484. my ($p_id, $value_array, $attr) = @_;
  1485. return $sth->set_err(1, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array))
  1486. if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY';
  1487. return $sth->set_err(1, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array")
  1488. unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here
  1489. return $sth->set_err(1, "Placeholder '$p_id' is out of range")
  1490. if $p_id <= 0; # can't easily/reliably test for too big
  1491. # get/create arrayref to hold params
  1492. my $hash_of_arrays = $sth->{ParamArrays} ||= { };
  1493. # If the bind has attribs then we rely on the driver conforming to
  1494. # the DBI spec in that a single bind_param() call with those attribs
  1495. # makes them 'sticky' and apply to all later execute(@values) calls.
  1496. # Since we only call bind_param() if we're given attribs then
  1497. # applications using drivers that don't support bind_param can still
  1498. # use bind_param_array() so long as they don't pass any attribs.
  1499. $$hash_of_arrays{$p_id} = $value_array;
  1500. return $sth->bind_param($p_id, undef, $attr)
  1501. if $attr;
  1502. 1;
  1503. }
  1504. sub bind_param_inout_array {
  1505. my $sth = shift;
  1506. # XXX not supported so we just call bind_param_array instead
  1507. # and then return an error
  1508. my ($p_num, $value_array, $attr) = @_;
  1509. $sth->bind_param_array($p_num, $value_array, $attr);
  1510. return $sth->set_err(1, "bind_param_inout_array not supported");
  1511. }
  1512. sub bind_columns {
  1513. my $sth = shift;
  1514. my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0;
  1515. if ($fields <= 0 && !$sth->{Active}) {
  1516. return $sth->set_err(1, "Statement has no result columns to bind"
  1517. ." (perhaps you need to successfully call execute first)");
  1518. }
  1519. # Backwards compatibility for old-style call with attribute hash
  1520. # ref as first arg. Skip arg if undef or a hash ref.
  1521. my $attr;
  1522. $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH';
  1523. die "bind_columns called with ".@_." refs when $fields needed."
  1524. if @_ != $fields;
  1525. my $idx = 0;
  1526. $sth->bind_col(++$idx, shift, $attr) or return
  1527. while (@_);
  1528. return 1;
  1529. }
  1530. sub execute_array {
  1531. my $sth = shift;
  1532. my ($attr, @array_of_arrays) = @_;
  1533. my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point
  1534. # get tuple status array or hash attribute
  1535. my $tuple_sts = $attr->{ArrayTupleStatus};
  1536. return $sth->set_err(1, "ArrayTupleStatus attribute must be an arrayref")
  1537. if $tuple_sts and ref $tuple_sts ne 'ARRAY';
  1538. # bind all supplied arrays
  1539. if (@array_of_arrays) {
  1540. $sth->{ParamArrays} = { }; # clear out old params
  1541. return $sth->set_err(1,
  1542. @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected")
  1543. if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS;
  1544. $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return
  1545. foreach (1..@array_of_arrays);
  1546. }
  1547. my $fetch_tuple_sub;
  1548. if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand
  1549. return $sth->set_err(1,
  1550. "Can't use both ArrayTupleFetch and explicit bind values")
  1551. if @array_of_arrays; # previous bind_param_array calls will simply be ignored
  1552. if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) {
  1553. my $fetch_sth = $fetch_tuple_sub;
  1554. return $sth->set_err(1,
  1555. "ArrayTupleFetch sth is not Active, need to execute() it first")
  1556. unless $fetch_sth->{Active};
  1557. # check column count match to give more friendly message
  1558. my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS};
  1559. return $sth->set_err(1,
  1560. "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected")
  1561. if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS)
  1562. && $NUM_OF_FIELDS != $NUM_OF_PARAMS;
  1563. $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref };
  1564. }
  1565. elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) {
  1566. return $sth->set_err(1, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle");
  1567. }
  1568. }
  1569. else {
  1570. my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} };
  1571. return $sth->set_err(1,
  1572. "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected")
  1573. if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given;
  1574. # get the length of a bound array
  1575. my $maxlen;
  1576. my %hash_of_arrays = %{$sth->{ParamArrays}};
  1577. foreach (keys(%hash_of_arrays)) {
  1578. my $ary = $hash_of_arrays{$_};
  1579. next unless ref $ary eq 'ARRAY';
  1580. $maxlen = @$ary if !$maxlen || @$ary > $maxlen;
  1581. }
  1582. # if there are no arrays then execute scalars once
  1583. $maxlen = 1 unless defined $maxlen;
  1584. my @bind_ids = 1..keys(%hash_of_arrays);
  1585. my $tuple_idx = 0;
  1586. $fetch_tuple_sub = sub {
  1587. return if $tuple_idx >= $maxlen;
  1588. my @tuple = map {
  1589. my $a = $hash_of_arrays{$_};
  1590. ref($a) ? $a->[$tuple_idx] : $a
  1591. } @bind_ids;
  1592. ++$tuple_idx;
  1593. return \@tuple;
  1594. };
  1595. }
  1596. return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts);
  1597. }
  1598. sub execute_for_fetch {
  1599. my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
  1600. # start with empty status array
  1601. ($tuple_status) ? @$tuple_status = () : $tuple_status = [];
  1602. my ($err_count, %errstr_cache);
  1603. while ( my $tuple = &$fetch_tuple_sub() ) {
  1604. if ( my $rc = $sth->execute(@$tuple) ) {
  1605. push @$tuple_status, $rc;
  1606. }
  1607. else {
  1608. $err_count++;
  1609. my $err = $sth->err;
  1610. push @$tuple_status, [ $err, $errstr_cache{$err} ||= $sth->errstr, $sth->state ];
  1611. }
  1612. }
  1613. return ($err_count) ? undef : scalar(@$tuple_status)||"0E0";
  1614. }
  1615. sub fetchall_arrayref { # ALSO IN Driver.xst
  1616. my ($sth, $slice, $max_rows) = @_;
  1617. $max_rows = -1 unless defined $max_rows;
  1618. my $mode = ref($slice) || 'ARRAY';
  1619. my @rows;
  1620. my $row;
  1621. if ($mode eq 'ARRAY') {
  1622. # we copy the array here because fetch (currently) always
  1623. # returns the same array ref. XXX
  1624. if ($slice && @$slice) {
  1625. $max_rows = -1 unless defined $max_rows;
  1626. push @rows, [ @{$row}[ @$slice] ]
  1627. while($max_rows-- and $row = $sth->fetch);
  1628. }
  1629. elsif (defined $max_rows) {
  1630. $max_rows = -1 unless defined $max_rows;
  1631. push @rows, [ @$row ]
  1632. while($max_rows-- and $row = $sth->fetch);
  1633. }
  1634. else {
  1635. push @rows, [ @$row ] while($row = $sth->fetch);
  1636. }
  1637. }
  1638. elsif ($mode eq 'HASH') {
  1639. $max_rows = -1 unless defined $max_rows;
  1640. if (keys %$slice) {
  1641. my @o_keys = keys %$slice;
  1642. my @i_keys = map { lc } keys %$slice;
  1643. while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) {
  1644. my %hash;
  1645. @hash{@o_keys} = @{$row}{@i_keys};
  1646. push @rows, \%hash;
  1647. }
  1648. }
  1649. else {
  1650. # XXX assumes new ref each fetchhash
  1651. push @rows, $row
  1652. while ($max_rows-- and $row = $sth->fetchrow_hashref());
  1653. }
  1654. }
  1655. else { Carp::croak("fetchall_arrayref($mode) invalid") }
  1656. return \@rows;
  1657. }
  1658. sub fetchall_hashref { # XXX may be better to fetchall_arrayref then convert to hashes
  1659. my ($sth, $key_field) = @_;
  1660. my $hash_key_name = $sth->{FetchHashKeyName};
  1661. my $names_hash = $sth->FETCH("${hash_key_name}_hash");
  1662. my $index = $names_hash->{$key_field}; # perl index not column number
  1663. ++$index if defined $index; # convert to column number
  1664. $index ||= $key_field if DBI::looks_like_number($key_field) && $key_field>=1;
  1665. return $sth->set_err(1, "Field '$key_field' does not exist (not one of @{[keys %$names_hash]})")
  1666. unless defined $index;
  1667. my $key_value;
  1668. $sth->bind_col($index, \$key_value) or return;
  1669. my %rows;
  1670. while (my $row = $sth->fetchrow_hashref($hash_key_name)) {
  1671. $rows{ $key_value } = $row;
  1672. }
  1673. return \%rows;
  1674. }
  1675. *dump_results = \&DBI::dump_results;
  1676. sub blob_copy_to_file { # returns length or undef on error
  1677. my($self, $field, $filename_or_handleref, $blocksize) = @_;
  1678. my $fh = $filename_or_handleref;
  1679. my($len, $buf) = (0, "");
  1680. $blocksize ||= 512; # not too ambitious
  1681. local(*FH);
  1682. unless(ref $fh) {
  1683. open(FH, ">$fh") || return undef;
  1684. $fh = \*FH;
  1685. }
  1686. while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
  1687. print $fh $buf;
  1688. $len += length $buf;
  1689. }
  1690. close(FH);
  1691. $len;
  1692. }
  1693. sub more_results {
  1694. shift->{syb_more_results}; # handy grandfathering
  1695. }
  1696. }
  1697. unless ($DBI::PurePerl) { # See install_driver
  1698. { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); }
  1699. { @DBD::_mem::db::ISA = qw(DBD::_mem::common); }
  1700. { @DBD::_mem::st::ISA = qw(DBD::_mem::common); }
  1701. # DBD::_mem::common::DESTROY is implemented in DBI.xs
  1702. }
  1703. 1;
  1704. __END__
  1705. =head1 DESCRIPTION
  1706. The DBI is a database access module for the Perl programming language. It defines
  1707. a set of methods, variables, and conventions that provide a consistent
  1708. database interface, independent of the actual database being used.
  1709. It is important to remember that the DBI is just an interface.
  1710. The DBI is a layer
  1711. of "glue" between an application and one or more database I<driver>
  1712. modules. It is the driver modules which do most of the real work. The DBI
  1713. provides a standard interface and framework for the drivers to operate
  1714. within.
  1715. =head2 Architecture of a DBI Application
  1716. |<- Scope of DBI ->|
  1717. .-. .--------------. .-------------.
  1718. .-------. | |---| XYZ Driver |---| XYZ Engine |
  1719. | Perl | | | `--------------' `-------------'
  1720. | script| |A| |D| .--------------. .-------------.
  1721. | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
  1722. | DBI | |I| |I| `--------------' `-------------'
  1723. | API | | |...
  1724. |methods| | |... Other drivers
  1725. `-------' | |...
  1726. `-'
  1727. The API, or Application Programming Interface, defines the
  1728. call interface and variables for Perl scripts to use. The API
  1729. is implemented by the Perl DBI extension.
  1730. The DBI "dispatches" the method calls to the appropriate driver for
  1731. actual execution. The DBI is also responsible for the dynamic loading
  1732. of drivers, error checking and handling, providing default
  1733. implementations for methods, and many other non-database specific duties.
  1734. Each driver
  1735. contains implementations of the DBI methods using the
  1736. private interface functions of the corresponding database engine. Only authors
  1737. of sophisticated/multi-database applications or generic library
  1738. functions need be concerned with drivers.
  1739. =head2 Notation and Conventions
  1740. The following conventions are used in this document:
  1741. $dbh Database handle object
  1742. $sth Statement handle object
  1743. $drh Driver handle object (rarely seen or used in applications)
  1744. $h Any of the handle types above ($dbh, $sth, or $drh)
  1745. $rc General Return Code (boolean: true=ok, false=error)
  1746. $rv General Return Value (typically an integer)
  1747. @ary List of values returned from the database, typically a row of data
  1748. $rows Number of rows processed (if available, else -1)
  1749. $fh A filehandle
  1750. undef NULL values are represented by undefined values in Perl
  1751. \%attr Reference to a hash of attribute values passed to methods
  1752. Note that Perl will automatically destroy database and statement handle objects
  1753. if all references to them are deleted.
  1754. =head2 Outline Usage
  1755. To use DBI,
  1756. first you need to load the DBI module:
  1757. use DBI;
  1758. use strict;
  1759. (The C<use strict;> isn't required but is strongly recommended.)
  1760. Then you need to L</connect> to your data source and get a I<handle> for that
  1761. connection:
  1762. $dbh = DBI->connect($dsn, $user, $password,
  1763. { RaiseError => 1, AutoCommit => 0 });
  1764. Since connecting can be expensive, you generally just connect at the
  1765. start of your program and disconnect at the end.
  1766. Explicitly defining the required C<AutoCommit> behaviour is strongly
  1767. recommended and may become mandatory in a later version. This
  1768. determines whether changes are automatically committed to the
  1769. database when executed, or need to be explicitly committed later.
  1770. The DBI allows an application to "prepare" statements for later
  1771. execution. A prepared statement is identified by a statement handle
  1772. held in a Perl variable.
  1773. We'll call the Perl variable C<$sth> in our examples.
  1774. The typical method call sequence for a C<SELECT> statement is:
  1775. prepare,
  1776. execute, fetch, fetch, ...
  1777. execute, fetch, fetch, ...
  1778. execute, fetch, fetch, ...
  1779. for example:
  1780. $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
  1781. $sth->execute( $baz );
  1782. while ( @row = $sth->fetchrow_array ) {
  1783. print "@row\n";
  1784. }
  1785. The typical method call sequence for a I<non>-C<SELECT> statement is:
  1786. prepare,
  1787. execute,
  1788. execute,
  1789. execute.
  1790. for example:
  1791. $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
  1792. while(<CSV>) {
  1793. chomp;
  1794. my ($foo,$bar,$baz) = split /,/;
  1795. $sth->execute( $foo, $bar, $baz );
  1796. }
  1797. The C<do()> method can be used for non repeated I<non>-C<SELECT> statement
  1798. (or with drivers that don't support placeholders):
  1799. $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
  1800. To commit your changes to the database (when L</AutoCommit> is off):
  1801. $dbh->commit; # or call $dbh->rollback; to undo changes
  1802. Finally, when you have finished working with the data source, you should
  1803. L</disconnect> from it:
  1804. $dbh->disconnect;
  1805. =head2 General Interface Rules & Caveats
  1806. The DBI does not have a concept of a "current session". Every session
  1807. has a handle object (i.e., a C<$dbh>) returned from the C<connect> method.
  1808. That handle object is used to invoke database related methods.
  1809. Most data is returned to the Perl script as strings. (Null values are
  1810. returned as C<undef>.) This allows arbitrary precision numeric data to be
  1811. handled without loss of accuracy. Beware that Perl may not preserve
  1812. the same accuracy when the string is used as a number.
  1813. Dates and times are returned as character strings in the current
  1814. default format of the corresponding database engine. Time zone effects
  1815. are database/driver dependent.
  1816. Perl supports binary data in Perl strings, and the DBI will pass binary
  1817. data to and from the driver without change. It is up to the driver
  1818. implementors to decide how they wish to handle such binary data.
  1819. Most databases that understand multiple character sets have a
  1820. default global charset. Text stored in the database is, or should
  1821. be, stored in that charset; if not, then that's the fault of either
  1822. the database or the application that inserted the data. When text is
  1823. fetched it should be automatically converted to the charset of the
  1824. client, presumably based on the locale. If a driver needs to set a
  1825. flag to get that behaviour, then it should do so; it should not require
  1826. the application to do that.
  1827. Multiple SQL statements may not be combined in a single statement
  1828. handle (C<$sth>), although some databases and drivers do support this
  1829. (notably Sybase and SQL Server).
  1830. Non-sequential record reads are not supported in this version of the DBI.
  1831. In other words, records can only be fetched in the order that the
  1832. database returned them, and once fetched they are forgotten.
  1833. Positioned updates and deletes are not directly supported by the DBI.
  1834. See the description of the C<CursorName> attribute for an alternative.
  1835. Individual driver implementors are free to provide any private
  1836. functions and/or handle attributes that they feel are useful.
  1837. Private driver functions can be invoked using the DBI C<func()> method.
  1838. Private driver attributes are accessed just like standard attributes.
  1839. Many methods have an optional C<\%attr> parameter which can be used to
  1840. pass information to the driver implementing the method. Except where
  1841. specifically documented, the C<\%attr> parameter can only be used to pass
  1842. driver specific hints. In general, you can ignore C<\%attr> parameters
  1843. or pass it as C<undef>.
  1844. =head2 Naming Conventions and Name Space
  1845. The DBI package and all packages below it (C<DBI::*>) are reserved for
  1846. use by the DBI. Extensions and related modules use the C<DBIx::>
  1847. namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>).
  1848. Package names beginning with C<DBD::> are reserved for use
  1849. by DBI database drivers. All environment variables used by the DBI
  1850. or by individual DBDs begin with "C<DBI_>" or "C<DBD_>".
  1851. The letter case used for attribute names is significant and plays an
  1852. important part in the portability of DBI scripts. The case of the
  1853. attribute name is used to signify who defined the meaning of that name
  1854. and its values.
  1855. Case of name Has a meaning defined by
  1856. ------------ ------------------------
  1857. UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
  1858. MixedCase DBI API (portable), underscores are not used.
  1859. lower_case Driver or database engine specific (non-portable)
  1860. It is of the utmost importance that Driver developers only use
  1861. lowercase attribute names when defining private attributes. Private
  1862. attribute names must be prefixed with the driver name or suitable
  1863. abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc).
  1864. =head2 SQL - A Query Language
  1865. Most DBI drivers require applications to use a dialect of SQL
  1866. (Structured Query Language) to interact with the database engine.
  1867. The L</"Standards Reference Information"> section provides links
  1868. to useful information about SQL.
  1869. The DBI itself does not mandate or require any particular language to
  1870. be used; it is language independent. In ODBC terms, the DBI is in
  1871. "pass-thru" mode, although individual drivers might not be. The only requirement
  1872. is that queries and other statements must be expressed as a single
  1873. string of characters passed as the first argument to the L</prepare> or
  1874. L</do> methods.
  1875. For an interesting diversion on the I<real> history of RDBMS and SQL,
  1876. from the people who made it happen, see:
  1877. http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
  1878. Follow the "Full Contents" then "Intergalactic dataspeak" links for the
  1879. SQL history.
  1880. =head2 Placeholders and Bind Values
  1881. Some drivers support placeholders and bind values.
  1882. I<Placeholders>, also called parameter markers, are used to indicate
  1883. values in a database statement that will be supplied later,
  1884. before the prepared statement is executed. For example, an application
  1885. might use the following to insert a row of data into the SALES table:
  1886. INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
  1887. or the following, to select the description for a product:
  1888. SELECT description FROM products WHERE product_code = ?
  1889. The C<?> characters are the placeholders. The association of actual
  1890. values with placeholders is known as I<binding>, and the values are
  1891. referred to as I<bind values>.
  1892. Note that the C<?> is not enclosed in quotation marks, even when the
  1893. placeholder represents a string. Some drivers also allow placeholders
  1894. like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on)
  1895. in addition to C<?>, but their use is not portable.
  1896. With most drivers, placeholders can't be used for any element of a
  1897. statement that would prevent the database server from validating the
  1898. statement and creating a query execution plan for it. For example:
  1899. "SELECT name, age FROM ?" # wrong (will probably fail)
  1900. "SELECT name, ? FROM people" # wrong (but may not 'fail')
  1901. Also, placeholders can only represent single scalar values.
  1902. For example, the following
  1903. statement won't work as expected for more than one value:
  1904. "SELECT name, age FROM people WHERE name IN (?)" # wrong
  1905. "SELECT name, age FROM people WHERE name IN (?,?)" # two names
  1906. When using placeholders with the SQL C<LIKE> qualifier, you must
  1907. remember that the placeholder substitutes for the whole string.
  1908. So you should use "C<... LIKE ? ...>" and include any wildcard
  1909. characters in the value that you bind to the placeholder.
  1910. B<NULL Values>
  1911. Undefined values, or C<undef>, are used to indicate NULL values.
  1912. You can insert update columns with a NULL value as you would a
  1913. non-NULL value. Consider these examples that insert and update the
  1914. column C<product_code> with a NULL value:
  1915. $sth = $dbh->prepare(qq{
  1916. INSERT INTO people (name, age) VALUES (?, ?)
  1917. });
  1918. $sth->execute("Joe Bloggs", undef);
  1919. $sth = $dbh->prepare(qq{
  1920. UPDATE people SET age = ? WHERE name = ?
  1921. });
  1922. $sth->execute(undef, "Joe Bloggs");
  1923. However, care must be taken in the particular case of trying to use
  1924. NULL values to qualify a C<WHERE> clause. Consider:
  1925. SELECT name FROM people WHERE age = ?
  1926. Binding an C<undef> (NULL) to the placeholder will I<not> select rows
  1927. which have a NULL C<product_code>! At least for database engines that
  1928. conform to the SQL standard. Refer to the SQL manual for your database
  1929. engine or any SQL book for the reasons for this. To explicitly select
  1930. NULLs you have to say "C<WHERE product_code IS NULL>".
  1931. A common issue is to have a code fragment handle a value that could be
  1932. either C<defined> or C<undef> (non-NULL or NULL) in a C<WHERE> clause.
  1933. A general way to do this is:
  1934. if (defined $age) {
  1935. push @sql_qual, "age = ?";
  1936. push @sql_bind, $age;
  1937. }
  1938. else {
  1939. push @sql_qual, "age IS NULL";
  1940. }
  1941. $sth = $dbh->prepare(qq{
  1942. SELECT id FROM products WHERE }.join(" AND ", @sql_qual).qq{
  1943. });
  1944. $sth->execute(@sql_bind);
  1945. If your WHERE clause contains many "NULLs-allowed" columns, you'll
  1946. need to manage many combinations of statements and this approach
  1947. rapidly becomes more complex.
  1948. A better solution would be to design a single C<WHERE> clause that
  1949. supports both NULL and non-NULL comparisons. Several examples of
  1950. C<WHERE> clauses that do this are presented below. But each example
  1951. lacks portability, robustness, or simplicity. Whether an example
  1952. is supported on your database engine depends on what SQL extensions it
  1953. supports, and where it can support the C<?> parameter in a statement.
  1954. 0) age = ?
  1955. 1) NVL(age, xx) = NVL(?, xx)
  1956. 2) ISNULL(age, xx) = ISNULL(?, xx)
  1957. 3) DECODE(age, ?, 1, 0) = 1
  1958. 4) age = ? OR (age IS NULL AND ? IS NULL)
  1959. 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1)
  1960. 6) age = ? OR (age IS NULL AND ? = 1)
  1961. Statements formed with the above C<WHERE> clauses require execute
  1962. statements as follows:
  1963. 0-3) $sth->execute($age);
  1964. 4,5) $sth->execute($age, $age);
  1965. 6) $sth->execute($age, defined($age)?0:1);
  1966. Example 0 should not work (as mentioned earlier), but may work on
  1967. a few database engines anyway.
  1968. Examples 1 and 2 are not robust: they require that you provide a
  1969. valid column value xx (e.g. '~') which is not present in any row.
  1970. That means you must have some notion of what data won't be stored
  1971. in the column, and expect clients to adhere to that.
  1972. Example 5 requires that you provide a stored procedure (SP_ISNULL
  1973. in this example) that acts as a function: it checks whether a value
  1974. is null, and returns 1 if it is, or 0 if not.
  1975. Example 6, the least simple, is probably the most portable, i.e., it
  1976. should work with with most, if not all, database engines.
  1977. Here is a table that indicates which examples above are known to work on
  1978. various database engines:
  1979. -----Examples------
  1980. 0 1 2 3 4 5 6
  1981. - - - - - - -
  1982. Oracle 9 N Y
  1983. Informix N N N Y N Y Y
  1984. MS SQL
  1985. DB2
  1986. Sybase
  1987. MySQL 4
  1988. DBI provides a sample perl script that will test the examples above
  1989. on your database engine and tell you which ones work. It is located
  1990. in the F<ex/> subdirectory of the DBI source distribution, or here:
  1991. L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl>
  1992. Please use the script to help us fill-in and maintain this table.
  1993. B<Performance>
  1994. Without using placeholders, the insert statement shown previously would have to
  1995. contain the literal values to be inserted and would have to be
  1996. re-prepared and re-executed for each row. With placeholders, the insert
  1997. statement only needs to be prepared once. The bind values for each row
  1998. can be given to the C<execute> method each time it's called. By avoiding
  1999. the need to re-prepare the statement for each row, the application
  2000. typically runs many times faster. Here's an example:
  2001. my $sth = $dbh->prepare(q{
  2002. INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
  2003. }) or die $dbh->errstr;
  2004. while (<>) {
  2005. chomp;
  2006. my ($product_code, $qty, $price) = split /,/;
  2007. $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
  2008. }
  2009. $dbh->commit or die $dbh->errstr;
  2010. See L</execute> and L</bind_param> for more details.
  2011. The C<q{...}> style quoting used in this example avoids clashing with
  2012. quotes that may be used in the SQL statement. Use the double-quote like
  2013. C<qq{...}> operator if you want to interpolate variables into the string.
  2014. See L<perlop/"Quote and Quote-like Operators"> for more details.
  2015. See also the L</bind_columns> method, which is used to associate Perl
  2016. variables with the output columns of a C<SELECT> statement.
  2017. =head1 THE DBI PACKAGE AND CLASS
  2018. In this section, we cover the DBI class methods, utility functions,
  2019. and the dynamic attributes associated with generic DBI handles.
  2020. =head2 DBI Constants
  2021. Constants representing the values of the SQL standard types can be
  2022. imported individually by name, or all together by importing the
  2023. special C<:sql_types> tag.
  2024. The names and values of all the defined SQL standard types can be
  2025. produced like this:
  2026. foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
  2027. printf "%s=%d\n", $_, &{"DBI::$_"};
  2028. }
  2029. These constants are defined by SQL/CLI, ODBC or both.
  2030. C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide
  2031. conflicting codes.
  2032. See the L</type_info>, L</type_info_all>, and L</bind_param> methods
  2033. for possible uses.
  2034. Note that just because the DBI defines a named constant for a given
  2035. data type doesn't mean that drivers will support that data type.
  2036. =head2 DBI Class Methods
  2037. The following methods are provided by the DBI class:
  2038. =over 4
  2039. =item C<parse_dsn>
  2040. ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn)
  2041. or die "Can't parse DBI DSN '$dsn'";
  2042. Breaks apart a DBI Data Source Name (DSN) and returns the individual
  2043. parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns
  2044. an empty list.
  2045. $scheme is the first part of the DSN and is currently always 'dbi'.
  2046. $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER},
  2047. and may be undefined. $attr_string is the optional attribute string,
  2048. which may be undefined. If $attr_string is true then $attr_hash
  2049. is a reference to a hash containing the parsed attribute names and
  2050. values. $driver_dsn is the last part of the DBI DSN string.
  2051. The parse_dsn() method was added in DBI 1.43.
  2052. =item C<connect>
  2053. $dbh = DBI->connect($data_source, $username, $password)
  2054. or die $DBI::errstr;
  2055. $dbh = DBI->connect($data_source, $username, $password, \%attr)
  2056. or die $DBI::errstr;
  2057. Establishes a database connection, or session, to the requested C<$data_source>.
  2058. Returns a database handle object if the connection succeeds. Use
  2059. C<$dbh-E<gt>disconnect> to terminate the connection.
  2060. If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err>
  2061. and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally
  2062. test the return status of C<connect> and C<print $DBI::errstr> if it has failed.
  2063. Multiple simultaneous connections to multiple databases through multiple
  2064. drivers can be made via the DBI. Simply make one C<connect> call for each
  2065. database and keep a copy of each returned database handle.
  2066. The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>".
  2067. The I<driver_name> specifies the driver that will be used to make the
  2068. connection. (Letter case is significant.)
  2069. As a convenience, if the C<$data_source> parameter is undefined or empty,
  2070. the DBI will substitute the value of the environment variable C<DBI_DSN>.
  2071. If just the I<driver_name> part is empty (i.e., the C<$data_source>
  2072. prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is
  2073. used. If neither variable is set, then C<connect> dies.
  2074. Examples of C<$data_source> values are:
  2075. dbi:DriverName:database_name
  2076. dbi:DriverName:database_name@hostname:port
  2077. dbi:DriverName:database=database_name;host=hostname;port=port
  2078. There is I<no standard> for the text following the driver name. Each
  2079. driver is free to use whatever syntax it wants. The only requirement the
  2080. DBI makes is that all the information is supplied in a single string.
  2081. You must consult the documentation for the drivers you are using for a
  2082. description of the syntax they require.
  2083. It is recommended that drivers support the ODBC style, shown in the
  2084. last example above. It is also recommended that that they support the
  2085. three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>'
  2086. as an alias for C<database>). This simplifies automatic construction
  2087. of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">.
  2088. Drivers should aim to 'do something reasonable' when given a DSN
  2089. in this form, but if any part is meaningless for that driver (such
  2090. as 'port' for Informix) it should generate an error if that part
  2091. is not empty.
  2092. If the environment variable C<DBI_AUTOPROXY> is defined (and the
  2093. driver in C<$data_source> is not "C<Proxy>") then the connect request
  2094. will automatically be changed to:
  2095. $ENV{DBI_AUTOPROXY};dsn=$data_source
  2096. C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>".
  2097. If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:"
  2098. will be prepended to it first. See the DBD::Proxy documentation
  2099. for more details.
  2100. If C<$username> or C<$password> are undefined (rather than just empty),
  2101. then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS>
  2102. environment variables, respectively. The DBI will warn if the
  2103. environment variables are not defined. However, the everyday use
  2104. of these environment variables is not recommended for security
  2105. reasons. The mechanism is primarily intended to simplify testing.
  2106. See below for alternative way to specify the username and password.
  2107. C<DBI-E<gt>connect> automatically installs the driver if it has not been
  2108. installed yet. Driver installation either returns a valid driver
  2109. handle, or it I<dies> with an error message that includes the string
  2110. "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect>
  2111. will die
  2112. on a driver installation failure and will only return C<undef> on a
  2113. connect failure, in which case C<$DBI::errstr> will hold the error message.
  2114. Use C<eval { ... }> if you need to catch the "C<install_driver>" error.
  2115. The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the
  2116. C<$username> and C<$password> arguments are then passed to the driver for
  2117. processing. The DBI does not define any interpretation for the
  2118. contents of these fields. The driver is free to interpret the
  2119. C<$data_source>, C<$username>, and C<$password> fields in any way, and supply
  2120. whatever defaults are appropriate for the engine being accessed.
  2121. (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment
  2122. variables if no C<$data_source> is specified.)
  2123. The C<AutoCommit> and C<PrintError> attributes for each connection
  2124. default to "on". (See L</AutoCommit> and L</PrintError> for more information.)
  2125. However, it is strongly recommended that you explicitly define C<AutoCommit>
  2126. rather than rely on the default. The C<PrintWarn> attribute defaults to
  2127. on if $^W is true, i.e., perl is running with warnings enabled.
  2128. The C<\%attr> parameter can be used to alter the default settings of
  2129. C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example:
  2130. $dbh = DBI->connect($data_source, $user, $pass, {
  2131. PrintError => 0,
  2132. AutoCommit => 0
  2133. });
  2134. The username and password can also be specified using the attributes
  2135. C<Username> and C<Password>, in which case they take precedence
  2136. over the C<$username> and C<$password> parameters.
  2137. You can also define connection attribute values within the C<$data_source>
  2138. parameter. For example:
  2139. dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...
  2140. Individual attributes values specified in this way take precedence over
  2141. any conflicting values specified via the C<\%attr> parameter to C<connect>.
  2142. The C<dbi_connect_method> attribute can be used to specify which driver
  2143. method should be called to establish the connection. The only useful
  2144. values are 'connect', 'connect_cached', or some specialized case like
  2145. 'Apache::DBI::connect' (which is automatically the default when running
  2146. within Apache).
  2147. Where possible, each session (C<$dbh>) is independent from the transactions
  2148. in other sessions. This is useful when you need to hold cursors open
  2149. across transactions--for example, if you use one session for your long lifespan
  2150. cursors (typically read-only) and another for your short update
  2151. transactions.
  2152. For compatibility with old DBI scripts, the driver can be specified by
  2153. passing its name as the fourth argument to C<connect> (instead of C<\%attr>):
  2154. $dbh = DBI->connect($data_source, $user, $pass, $driver);
  2155. In this "old-style" form of C<connect>, the C<$data_source> should not start
  2156. with "C<dbi:driver_name:>". (If it does, the embedded driver_name
  2157. will be ignored). Also note that in this older form of C<connect>,
  2158. the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the
  2159. C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME>
  2160. environment variable is
  2161. checked if C<DBI_DSN> is not defined. Beware that this "old-style"
  2162. C<connect> will soon be withdrawn in a future version of DBI.
  2163. =item C<connect_cached>
  2164. $dbh = DBI->connect_cached($data_source, $username, $password)
  2165. or die $DBI::errstr;
  2166. $dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
  2167. or die $DBI::errstr;
  2168. C<connect_cached> is like L</connect>, except that the database handle
  2169. returned is also
  2170. stored in a hash associated with the given parameters. If another call
  2171. is made to C<connect_cached> with the same parameter values, then the
  2172. corresponding cached C<$dbh> will be returned if it is still valid.
  2173. The cached database handle is replaced with a new connection if it
  2174. has been disconnected or if the C<ping> method fails.
  2175. Note that the behaviour of this method differs in several respects from the
  2176. behaviour of persistent connections implemented by Apache::DBI.
  2177. Caching connections can be useful in some applications, but it can
  2178. also cause problems, such as too many connections, and so should
  2179. be used with care. In particular, avoid changing the attributes of
  2180. a database handle created via connect_cached() because it will affect
  2181. other code that may be using the same handle.
  2182. Where multiple separate parts of a program are using connect_cached()
  2183. to connect to the same database with the same (initial) attributes
  2184. it is a good idea to add a private attribute to the connect_cached()
  2185. call to effectively limit the scope of the caching. For example:
  2186. DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... });
  2187. Handles returned from that connect_cached() call will only be returned
  2188. by other connect_cached() call elsewhere in the code if those other
  2189. calls also pass in the same attribute values, including the private one.
  2190. (I've used C<private_foo_cachekey> here as an example, you can use
  2191. any attribute name with a C<private_> prefix.)
  2192. Taking that one step further, you can limit a particular connect_cached()
  2193. call to return handles unique to that one place in the code by setting the
  2194. private attribute to a unique value for that place:
  2195. DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... });
  2196. By using a private attribute you still get connection caching for
  2197. the individual calls to connect_cached() but, by making separate
  2198. database conections for separate parts of the code, the database
  2199. handles are isolated from any attribute changes made to other handles.
  2200. The cache can be accessed (and cleared) via the L</CachedKids> attribute:
  2201. my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
  2202. %$CachedKids_hashref = () if $CachedKids_hashref;
  2203. =item C<available_drivers>
  2204. @ary = DBI->available_drivers;
  2205. @ary = DBI->available_drivers($quiet);
  2206. Returns a list of all available drivers by searching for C<DBD::*> modules
  2207. through the directories in C<@INC>. By default, a warning is given if
  2208. some drivers are hidden by others of the same name in earlier
  2209. directories. Passing a true value for C<$quiet> will inhibit the warning.
  2210. =item C<installed_versions>
  2211. DBI->installed_versions;
  2212. @ary = DBI->installed_versions;
  2213. %hash = DBI->installed_versions;
  2214. Calls available_drivers() and attempts to load each of them in turn
  2215. using install_driver(). For each load that succeeds the driver
  2216. name and version number are added to a hash. When running under
  2217. L<DBI::PurePerl> drivers which appear not be pure-perl are ignored.
  2218. When called in array context the list of successfully loaded drivers
  2219. is returned (without the 'DBD::' prefix).
  2220. When called in scalar context a reference to the hash is returned
  2221. and the hash will also contain other entries for the C<DBI> version,
  2222. C<OS> name, etc.
  2223. When called in a void context the installed_versions() method will
  2224. print out a formatted list of the hash contents, one per line.
  2225. Due to the potentially high memory cost and unknown risks of loading
  2226. in an unknown number of drivers that just happen to be installed
  2227. on the system, this method is nor recommended for general use.
  2228. Use available_drivers() instead.
  2229. The installed_versions() method is primarily intended as a quick
  2230. way to see from the command line what's installed. For example:
  2231. perl -MDBI -e 'DBI->installed_versions'
  2232. The installed_versions() method was added in DBI 1.38.
  2233. =item C<data_sources>
  2234. @ary = DBI->data_sources($driver);
  2235. @ary = DBI->data_sources($driver, \%attr);
  2236. Returns a list of data sources (databases) available via the named
  2237. driver. If C<$driver> is empty or C<undef>, then the value of the
  2238. C<DBI_DRIVER> environment variable is used.
  2239. The driver will be loaded if it hasn't been already. Note that if the
  2240. driver loading fails then data_sources() I<dies> with an error message
  2241. that includes the string "C<install_driver>" and the underlying problem.
  2242. Data sources are returned in a form suitable for passing to the
  2243. L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
  2244. Note that many drivers have no way of knowing what data sources might
  2245. be available for it. These drivers return an empty or incomplete list
  2246. or may require driver-specific attributes.
  2247. There is also a data_sources() method defined for database handles.
  2248. =item C<trace>
  2249. DBI->trace($trace_setting)
  2250. DBI->trace($trace_setting, $trace_filename)
  2251. $trace_setting = DBI->trace;
  2252. The C<DBI-E<gt>trace> method sets the I<global default> trace
  2253. settings and returns the I<previous> trace settings. It can also
  2254. be used to change where the trace output is sent.
  2255. There's a similar method, C<$h-E<gt>trace>, which sets the trace
  2256. settings for the specific handle it's called on.
  2257. See the L</TRACING> section for full details about the DBI's powerful
  2258. tracing facilities.
  2259. =back
  2260. =head2 DBI Utility Functions
  2261. In addition to the DBI methods listed in the previous section,
  2262. the DBI package also provides several utility functions.
  2263. These can be imported into your code by listing them in
  2264. the C<use> statement. For example:
  2265. use DBI qw(neat data_diff);
  2266. Alternatively, all these utility functions (except hash) can be
  2267. imported using the C<:utils> import tag. For example:
  2268. use DBI qw(:utils);
  2269. =over 4
  2270. =item C<data_string_desc>
  2271. $description = data_string_desc($string);
  2272. Returns an informal description of the string. For example:
  2273. UTF8 off, ASCII, 42 characters 42 bytes
  2274. UTF8 off, non-ASCII, 42 characters 42 bytes
  2275. UTF8 on, non-ASCII, 4 characters 6 bytes
  2276. UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes
  2277. UTF8 off, undef
  2278. The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag.
  2279. If $string has the SvUTF8 flag set but the sequence of bytes it
  2280. contains are not a valid UTF-8 encoding then data_string_desc()
  2281. will report C<UTF8 on but INVALID encoding>.
  2282. The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the
  2283. characters in the string are ASCII (have code points <= 127).
  2284. The data_string_desc() function was added in DBI 1.46.
  2285. =item C<data_string_diff>
  2286. $diff = data_string_diff($a, $b);
  2287. Returns an informal description of the first character difference
  2288. between the strings. If both $a and $b contain the same sequence
  2289. of characters then data_string_diff() returns an empty string.
  2290. For example:
  2291. Params a & b Result
  2292. ------------ ------
  2293. 'aaa', 'aaa' ''
  2294. 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b'
  2295. 'aaa', undef 'String b is undef, string a has 3 characters'
  2296. 'aaa', 'aa' 'String b truncated after 2 characters'
  2297. Unicode characters are reported in C<\x{XXXX}> format. Unicode
  2298. code points in the range U+0800 to U+08FF are unassigned and most
  2299. likely to occur due to double-encoding. Characters in this range
  2300. are reported as C<\x{08XX}='C'> where C<C> is the corresponding
  2301. latin-1 character.
  2302. The data_string_diff() function only considers logical I<characters>
  2303. and not the underlying encoding. See L</data_diff> for an alternative.
  2304. The data_string_diff() function was added in DBI 1.46.
  2305. =item C<data_diff>
  2306. $diff = data_diff($a, $b);
  2307. $diff = data_diff($a, $b, $logical);
  2308. Returns an informal description of the difference between two strings.
  2309. It calls L</data_string_desc> and L</data_string_diff>
  2310. and returns the combined results as a multi-line string.
  2311. For example, C<data_diff("abc", "ab\x{263a}")> will return:
  2312. a: UTF8 off, ASCII, 3 characters 3 bytes
  2313. b: UTF8 on, non-ASCII, 3 characters 5 bytes
  2314. Strings differ at index 2: a[2]=c, b[2]=\x{263A}
  2315. If $a and $b are identical in both the characters they contain I<and>
  2316. their physical encoding then data_diff() returns an empty string.
  2317. If $logical is true then physical encoding differences are ignored
  2318. (but are still reported if there is a difference in the characters).
  2319. The data_diff() function was added in DBI 1.46.
  2320. =item C<neat>
  2321. $str = neat($value);
  2322. $str = neat($value, $maxlen);
  2323. Return a string containing a neat (and tidy) representation of the
  2324. supplied value.
  2325. Strings will be quoted, although internal quotes will I<not> be escaped.
  2326. Values known to be numeric will be unquoted. Undefined (NULL) values
  2327. will be shown as C<undef> (without quotes).
  2328. If the string is flagged internally as utf8 then double quotes will
  2329. be used, otherwise single quotes are used and unprintable characters
  2330. will be replaced by dot (.).
  2331. For result strings longer than C<$maxlen> the result string will be
  2332. truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0
  2333. or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400.
  2334. This function is designed to format values for human consumption.
  2335. It is used internally by the DBI for L</trace> output. It should
  2336. typically I<not> be used for formatting values for database use.
  2337. (See also L</quote>.)
  2338. =item C<neat_list>
  2339. $str = neat_list(\@listref, $maxlen, $field_sep);
  2340. Calls C<neat> on each element of the list and returns a string
  2341. containing the results joined with C<$field_sep>. C<$field_sep> defaults
  2342. to C<", ">.
  2343. =item C<looks_like_number>
  2344. @bool = looks_like_number(@array);
  2345. Returns true for each element that looks like a number.
  2346. Returns false for each element that does not look like a number.
  2347. Returns C<undef> for each element that is undefined or empty.
  2348. =item C<hash>
  2349. $hash_value = DBI::hash($buffer, $type);
  2350. Return a 32-bit integer 'hash' value corresponding to the contents of $buffer.
  2351. The $type parameter selects which kind of hash algorithm should be used.
  2352. For the technically curious, type 0 (which is the default if $type
  2353. isn't specified) is based on the Perl 5.1 hash except that the value
  2354. is forced to be negative (for obscure historical reasons).
  2355. Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See
  2356. L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information.
  2357. Both types are implemented in C and are very fast.
  2358. This function doesn't have much to do with databases, except that
  2359. it can be handy to store hash values in a database.
  2360. =back
  2361. =head2 DBI Dynamic Attributes
  2362. Dynamic attributes are always associated with the I<last handle used>
  2363. (that handle is represented by C<$h> in the descriptions below).
  2364. Where an attribute is equivalent to a method call, then refer to
  2365. the method call for all related documentation.
  2366. Warning: these attributes are provided as a convenience but they
  2367. do have limitations. Specifically, they have a short lifespan:
  2368. because they are associated with
  2369. the last handle used, they should only be used I<immediately> after
  2370. calling the method that "sets" them.
  2371. If in any doubt, use the corresponding method call.
  2372. =over 4
  2373. =item C<$DBI::err>
  2374. Equivalent to C<$h-E<gt>err>.
  2375. =item C<$DBI::errstr>
  2376. Equivalent to C<$h-E<gt>errstr>.
  2377. =item C<$DBI::state>
  2378. Equivalent to C<$h-E<gt>state>.
  2379. =item C<$DBI::rows>
  2380. Equivalent to C<$h-E<gt>rows>. Please refer to the documentation
  2381. for the L</rows> method.
  2382. =item C<$DBI::lasth>
  2383. Returns the DBI object handle used for the most recent DBI method call.
  2384. If the last DBI method call was a DESTROY then $DBI::lasth will return
  2385. the handle of the parent of the destroyed handle, if there is one.
  2386. =back
  2387. =head1 METHODS COMMON TO ALL HANDLES
  2388. The following methods can be used by all types of DBI handles.
  2389. =over 4
  2390. =item C<err>
  2391. $rv = $h->err;
  2392. Returns the I<native> database engine error code from the last driver
  2393. method called. The code is typically an integer but you should not
  2394. assume that.
  2395. The DBI resets $h->err to undef before most DBI method calls, so the
  2396. value only has a short lifespan. Also, for most drivers, the statement
  2397. handles share the same error variable as the parent database handle,
  2398. so calling a method on one handle may reset the error on the
  2399. related handles.
  2400. If you need to test for individual errors I<and> have your program be
  2401. portable to different database engines, then you'll need to determine
  2402. what the corresponding error codes are for all those engines and test for
  2403. all of them.
  2404. A driver may return C<0> from err() to indicate a warning condition
  2405. after a method call. Similarly, a driver may return an empty string
  2406. to indicate a 'success with information' condition. In both these
  2407. cases the value is false but not undef. The errstr() and state()
  2408. methods may be used to retrieve extra information in these cases.
  2409. See L</set_err> for more information.
  2410. =item C<errstr>
  2411. $str = $h->errstr;
  2412. Returns the native database engine error message from the last DBI
  2413. method called. This has the same lifespan issues as the L</err> method
  2414. described above.
  2415. The returned string may contain multiple messages separated by
  2416. newline characters.
  2417. The errstr() method should not be used to test for errors, use err()
  2418. for that, because drivers may return 'success with information' or
  2419. warning messages via errstr() for methods that have not 'failed'.
  2420. See L</set_err> for more information.
  2421. =item C<state>
  2422. $str = $h->state;
  2423. Returns a state code in the standard SQLSTATE five character format.
  2424. Note that the specific success code C<00000> is translated to any empty string
  2425. (false). If the driver does not support SQLSTATE (and most don't),
  2426. then state will return C<S1000> (General Error) for all errors.
  2427. The driver is free to return any value via C<state>, e.g., warning
  2428. codes, even if it has not declared an error by returning a true value
  2429. via the L</err> method described above.
  2430. The state() method should not be used to test for errors, use err()
  2431. for that, because drivers may return a 'success with information' or
  2432. warning state code via errstr() for methods that have not 'failed'.
  2433. =item C<set_err>
  2434. $rv = $h->set_err($err, $errstr);
  2435. $rv = $h->set_err($err, $errstr, $state);
  2436. $rv = $h->set_err($err, $errstr, $state, $method);
  2437. $rv = $h->set_err($err, $errstr, $state, $method, $rv);
  2438. Set the C<err>, C<errstr>, and C<state> values for the handle.
  2439. This method is typically only used by DBI drivers and DBI subclasses.
  2440. If the L</HandleSetErr> attribute holds a reference to a subroutine
  2441. it is called first. The subroutine can alter the $err, $errstr, $state,
  2442. and $method values. See L</HandleSetErr> for full details.
  2443. If the subroutine returns a true value then the handle C<err>,
  2444. C<errstr>, and C<state> values are not altered and set_err() returns
  2445. an empty list (it normally returns $rv which defaults to undef, see below).
  2446. Setting C<err> to a I<true> value indicates an error and will trigger
  2447. the normal DBI error handling mechanisms, such as C<RaiseError> and
  2448. C<HandleError>, if they are enabled, when execution returns from
  2449. the DBI back to the application.
  2450. Setting C<err> to C<""> indicates an 'information' state, and setting
  2451. it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef>
  2452. also sets C<errstr> to undef, and C<state> to C<"">, irrespective
  2453. of the values of the $errstr and $state parameters.
  2454. The $method parameter provides an alternate method name for the
  2455. C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of
  2456. the fairly unhelpful 'C<set_err>'.
  2457. The C<set_err> method normally returns undef. The $rv parameter
  2458. provides an alternate return value.
  2459. Some special rules apply if the C<err> or C<errstr>
  2460. values for the handle are I<already> set...
  2461. If C<errstr> is true then: "C< [err was %s now %s]>" is appended if
  2462. $err is true and C<err> is already true; "C< [state was %s now %s]>"
  2463. is appended if $state is true and C<state> is already true; then
  2464. "C<\n>" and the new $errstr are appended. Obviously the C<%s>'s
  2465. above are replaced by the corresponding values.
  2466. The handle C<err> value is set to $err if: $err is true; or handle
  2467. C<err> value is undef; or $err is defined and the length is greater
  2468. than the handle C<err> length. The effect is that an 'information'
  2469. state only overrides undef; a 'warning' overrides undef or 'information',
  2470. and an 'error' state overrides anything.
  2471. The handle C<state> value is set to $state if $state is true and
  2472. the handle C<err> value was set (by the rules above).
  2473. Support for warning and information states was added in DBI 1.41.
  2474. =item C<trace>
  2475. $h->trace($trace_settings);
  2476. $h->trace($trace_settings, $trace_filename);
  2477. $trace_settings = $h->trace;
  2478. The trace() method is used to alter the trace settings for a handle
  2479. (and any future children of that handle). It can also be used to
  2480. change where the trace output is sent.
  2481. There's a similar method, C<DBI-E<gt>trace>, which sets the global
  2482. default trace settings.
  2483. See the L</TRACING> section for full details about the DBI's powerful
  2484. tracing facilities.
  2485. =item C<trace_msg>
  2486. $h->trace_msg($message_text);
  2487. $h->trace_msg($message_text, $min_level);
  2488. Writes C<$message_text> to the trace file if the trace level is
  2489. greater than or equal to $min_level (which defaults to 1).
  2490. Can also be called as C<DBI-E<gt>trace_msg($msg)>.
  2491. See L</TRACING> for more details.
  2492. =item C<func>
  2493. $h->func(@func_arguments, $func_name) or die ...;
  2494. The C<func> method can be used to call private non-standard and
  2495. non-portable methods implemented by the driver. Note that the function
  2496. name is given as the I<last> argument.
  2497. It's also important to note that the func() method does not clear
  2498. a previous error ($DBI::err etc.) and it does not trigger automatic
  2499. error detection (RaiseError etc.) so you must check the return
  2500. status and/or $h->err to detect errors.
  2501. (This method is not directly related to calling stored procedures.
  2502. Calling stored procedures is currently not defined by the DBI.
  2503. Some drivers, such as DBD::Oracle, support it in non-portable ways.
  2504. See driver documentation for more details.)
  2505. See also L</install_method> for how you can avoid needing to
  2506. use func() and gain.
  2507. =item C<can>
  2508. $is_implemented = $h->can($method_name);
  2509. Returns true if $method_name is implemented by the driver or a
  2510. default method is provided by the DBI.
  2511. It returns false where a driver hasn't implemented a method and the
  2512. default method is provided by the DBI is just an empty stub.
  2513. =item C<parse_trace_flags>
  2514. $trace_settings_integer = $h->parse_trace_flags($trace_settings);
  2515. Parses a string containing trace settings and returns the corresponding
  2516. integer value used internally by the DBI and drivers.
  2517. The $trace_settings argument is a string containing a trace level
  2518. between 0 and 15 and/or trace flag names separated by vertical bar
  2519. ("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">.
  2520. It uses the parse_trace_flag() method, described below, to process
  2521. the individual trage flag names.
  2522. The parse_trace_flags() method was added in DBI 1.42.
  2523. =item C<parse_trace_flag>
  2524. $bit_flag = $h->parse_trace_flag($trace_flag_name);
  2525. Returns the bit flag corresponding to the trace flag name in
  2526. $trace_flag_name. Drivers are expected to override this method and
  2527. check if $trace_flag_name is a driver specific trace flags and, if
  2528. not, then call the DBIs default parse_trace_flag().
  2529. The parse_trace_flag() method was added in DBI 1.42.
  2530. =item C<swap_inner_handle>
  2531. $rc = $h1->swap_inner_handle( $h2 );
  2532. $rc = $h1->swap_inner_handle( $h2, $allow_reparent );
  2533. Brain transplants for handles. You don't need to know about this
  2534. unless you want to become a handle surgeon.
  2535. A DBI handle is a reference to a tied hash. A tied hash has an
  2536. I<inner> hash that actually holds the contents. The swap_inner_handle()
  2537. method swaps the inner hashes between two handles. The $h1 and $h2
  2538. handles still point to the same tied hashes, but what those hashes
  2539. are tied to has been swapped. In effect $h1 I<becomes> $h2 and
  2540. vice-versa. This is powerful stuff. Use with care.
  2541. As a small safety measure, the two handles, $h1 and $h2, have to
  2542. share the same parent unless $allow_reparent is true.
  2543. The swap_inner_handle() method was added in DBI 1.44.
  2544. =back
  2545. =head1 ATTRIBUTES COMMON TO ALL HANDLES
  2546. These attributes are common to all types of DBI handles.
  2547. Some attributes are inherited by child handles. That is, the value
  2548. of an inherited attribute in a newly created statement handle is the
  2549. same as the value in the parent database handle. Changes to attributes
  2550. in the new statement handle do not affect the parent database handle
  2551. and changes to the database handle do not affect existing statement
  2552. handles, only future ones.
  2553. Attempting to set or get the value of an unknown attribute generates a warning,
  2554. except for private driver specific attributes (which all have names
  2555. starting with a lowercase letter).
  2556. Example:
  2557. $h->{AttributeName} = ...; # set/write
  2558. ... = $h->{AttributeName}; # get/read
  2559. =over 4
  2560. =item C<Warn> (boolean, inherited)
  2561. The C<Warn> attribute enables useful warnings for certain bad
  2562. practices. It is enabled by default and should only be disabled in
  2563. rare circumstances. Since warnings are generated using the Perl
  2564. C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}>
  2565. hook.
  2566. The C<Warn> attribute is not related to the C<PrintWarn> attribute.
  2567. =item C<Active> (boolean, read-only)
  2568. The C<Active> attribute is true if the handle object is "active". This is rarely used in
  2569. applications. The exact meaning of active is somewhat vague at the
  2570. moment. For a database handle it typically means that the handle is
  2571. connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For
  2572. a statement handle it typically means that the handle is a C<SELECT>
  2573. that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish>
  2574. sets C<Active> off.)
  2575. =item C<Executed> (boolean)
  2576. The C<Executed> attribute is true if the handle object has been "executed".
  2577. Currently only the $dbh do() method and the $sth execute(), execute_array(),
  2578. and execute_for_fetch() methods set the C<Executed> attribute.
  2579. When it's set on a handle it is also set on the parent handle at the
  2580. same time. So calling execute() on a $sth also sets the C<Executed>
  2581. attribute on the parent $dbh.
  2582. The C<Executed> attribute for a database handle is cleared by the
  2583. commit() and rollback() methods. The C<Executed> attribute of a
  2584. statement handle is not cleared by the DBI under any circumstances
  2585. and so acts as a permanent record of whether the statement handle
  2586. was ever used.
  2587. The C<Executed> attribute was added in DBI 1.41.
  2588. =item C<Kids> (integer, read-only)
  2589. For a driver handle, C<Kids> is the number of currently existing database
  2590. handles that were created from that driver handle. For a database
  2591. handle, C<Kids> is the number of currently existing statement handles that
  2592. were created from that database handle.
  2593. For a statement handle, the value is zero.
  2594. =item C<ActiveKids> (integer, read-only)
  2595. Like C<Kids>, but only counting those that are C<Active> (as above).
  2596. =item C<CachedKids> (hash ref)
  2597. For a database handle, C<CachedKids> returns a reference to the cache (hash) of
  2598. statement handles created by the L</prepare_cached> method. For a
  2599. driver handle, returns a reference to the cache (hash) of
  2600. database handles created by the L</connect_cached> method.
  2601. =item C<CompatMode> (boolean, inherited)
  2602. The C<CompatMode> attribute is used by emulation layers (such as
  2603. Oraperl) to enable compatible behaviour in the underlying driver
  2604. (e.g., DBD::Oracle) for this handle. Not normally set by application code.
  2605. It also has the effect of disabling the 'quick FETCH' of attribute
  2606. values from the handles attribute cache. So all attribute values
  2607. are handled by the drivers own FETCH method. This makes them slightly
  2608. slower but is useful for special-purpose drivers like DBD::Multiplex.
  2609. =item C<InactiveDestroy> (boolean)
  2610. The C<InactiveDestroy> attribute can be used to disable the I<database
  2611. engine> related effect of DESTROYing a handle (which would normally
  2612. close a prepared statement or disconnect from the database etc).
  2613. The default value, false, means a handle will be fully destroyed
  2614. when it passes out of scope.
  2615. For a database handle, this attribute does not disable an I<explicit>
  2616. call to the disconnect method, only the implicit call from DESTROY
  2617. that happens if the handle is still marked as C<Active>.
  2618. Think of the name as meaning 'treat the handle as not-Active in the
  2619. DESTROY method'.
  2620. This attribute is specifically designed for use in Unix applications
  2621. that "fork" child processes. Either the parent or the child process,
  2622. but not both, should set C<InactiveDestroy> on all their shared handles.
  2623. Note that some databases, including Oracle, don't support passing a
  2624. database connection across a fork.
  2625. To help tracing applications using fork the process id is shown in
  2626. the trace log whenever a DBI or handle trace() method is called.
  2627. The process id also shown for I<every> method call if the DBI trace
  2628. level (not handle trace level) is set high enough to show the trace
  2629. from the DBI's method dispatcher, e.g. >= 9.
  2630. =item C<PrintWarn> (boolean, inherited)
  2631. The C<PrintWarn> attribute controls the printing of warnings recorded
  2632. by the driver. When set to a true value the DBI will check method
  2633. calls to see if a warning condition has been set. If so, the DBI
  2634. will effectively do a C<warn("$class $method warning: $DBI::errstr")>
  2635. where C<$class> is the driver class and C<$method> is the name of
  2636. the method which failed. E.g.,
  2637. DBD::Oracle::db execute warning: ... warning text here ...
  2638. By default, C<DBI-E<gt>connect> sets C<PrintWarn> "on" if $^W is true,
  2639. i.e., perl is running with warnings enabled.
  2640. If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
  2641. handler or modules like CGI::Carp and CGI::ErrorWrap.
  2642. See also L</set_err> for how warnings are recorded and L</HandleSetErr>
  2643. for how to influence it.
  2644. Fetching the full details of warnings can require an extra round-trip
  2645. to the database server for some drivers. In which case the driver
  2646. may opt to only fetch the full details of warnings if the C<PrintWarn>
  2647. attribute is true. If C<PrintWarn> is false then these drivers should
  2648. still indicate the fact that there were warnings by setting the
  2649. warning string to, for example: "3 warnings".
  2650. =item C<PrintError> (boolean, inherited)
  2651. The C<PrintError> attribute can be used to force errors to generate warnings (using
  2652. C<warn>) in addition to returning error codes in the normal way. When set
  2653. "on", any method which results in an error occuring will cause the DBI to
  2654. effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class>
  2655. is the driver class and C<$method> is the name of the method which failed. E.g.,
  2656. DBD::Oracle::db prepare failed: ... error text here ...
  2657. By default, C<DBI-E<gt>connect> sets C<PrintError> "on".
  2658. If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
  2659. handler or modules like CGI::Carp and CGI::ErrorWrap.
  2660. =item C<RaiseError> (boolean, inherited)
  2661. The C<RaiseError> attribute can be used to force errors to raise exceptions rather
  2662. than simply return error codes in the normal way. It is "off" by default.
  2663. When set "on", any method which results in an error will cause
  2664. the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>,
  2665. where C<$class> is the driver class and C<$method> is the name of the method
  2666. that failed. E.g.,
  2667. DBD::Oracle::db prepare failed: ... error text here ...
  2668. If you turn C<RaiseError> on then you'd normally turn C<PrintError> off.
  2669. If C<PrintError> is also on, then the C<PrintError> is done first (naturally).
  2670. Typically C<RaiseError> is used in conjunction with C<eval { ... }>
  2671. to catch the exception that's been thrown and followed by an
  2672. C<if ($@) { ... }> block to handle the caught exception. In that eval
  2673. block the $DBI::lasth variable can be useful for diagnosis and reporting.
  2674. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
  2675. If you want to temporarily turn C<RaiseError> off (inside a library function
  2676. that is likely to fail, for example), the recommended way is like this:
  2677. {
  2678. local $h->{RaiseError}; # localize and turn off for this block
  2679. ...
  2680. }
  2681. The original value will automatically and reliably be restored by Perl,
  2682. regardless of how the block is exited.
  2683. The same logic applies to other attributes, including C<PrintError>.
  2684. =item C<HandleError> (code ref, inherited)
  2685. The C<HandleError> attribute can be used to provide your own alternative behaviour
  2686. in case of errors. If set to a reference to a subroutine then that
  2687. subroutine is called when an error is detected (at the same point that
  2688. C<RaiseError> and C<PrintError> are handled).
  2689. The subroutine is called with three parameters: the error message
  2690. string that C<RaiseError> and C<PrintError> would use,
  2691. the DBI handle being used, and the first value being returned by
  2692. the method that failed (typically undef).
  2693. If the subroutine returns a false value then the C<RaiseError>
  2694. and/or C<PrintError> attributes are checked and acted upon as normal.
  2695. For example, to C<die> with a full stack trace for any error:
  2696. use Carp;
  2697. $h->{HandleError} = sub { confess(shift) };
  2698. Or to turn errors into exceptions:
  2699. use Exception; # or your own favourite exception module
  2700. $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
  2701. It is possible to 'stack' multiple HandleError handlers by using
  2702. closures:
  2703. sub your_subroutine {
  2704. my $previous_handler = $h->{HandleError};
  2705. $h->{HandleError} = sub {
  2706. return 1 if $previous_handler and &$previous_handler(@_);
  2707. ... your code here ...
  2708. };
  2709. }
  2710. Using a C<my> inside a subroutine to store the previous C<HandleError>
  2711. value is important. See L<perlsub> and L<perlref> for more information
  2712. about I<closures>.
  2713. It is possible for C<HandleError> to alter the error message that
  2714. will be used by C<RaiseError> and C<PrintError> if it returns false.
  2715. It can do that by altering the value of $_[0]. This example appends
  2716. a stack trace to all errors and, unlike the previous example using
  2717. Carp::confess, this will work C<PrintError> as well as C<RaiseError>:
  2718. $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; };
  2719. It is also possible for C<HandleError> to hide an error, to a limited
  2720. degree, by using L</set_err> to reset $DBI::err and $DBI::errstr,
  2721. and altering the return value of the failed method. For example:
  2722. $h->{HandleError} = sub {
  2723. return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/;
  2724. return 0 unless $_[1]->err == 1234; # the error to 'hide'
  2725. $h->set_err(undef,undef); # turn off the error
  2726. $_[2] = [ ... ]; # supply alternative return value
  2727. return 1;
  2728. };
  2729. This only works for methods which return a single value and is hard
  2730. to make reliable (avoiding infinite loops, for example) and so isn't
  2731. recommended for general use! If you find a I<good> use for it then
  2732. please let me know.
  2733. =item C<HandleSetErr> (code ref, inherited)
  2734. The C<HandleSetErr> attribute can be used to intercept
  2735. the setting of handle C<err>, C<errstr>, and C<state> values.
  2736. If set to a reference to a subroutine then that subroutine is called
  2737. whenever set_err() is called, typically by the driver or a subclass.
  2738. The subroutine is called with five arguments, the first five that
  2739. were passed to set_err(): the handle, the C<err>, C<errstr>, and
  2740. C<state> values being set, and the method name. These can be altered
  2741. by changing the values in the @_ array. The return value affects
  2742. set_err() behaviour, see L</set_err> for details.
  2743. It is possible to 'stack' multiple HandleSetErr handlers by using
  2744. closures. See L</HandleError> for an example.
  2745. The C<HandleSetErr> and C<HandleError> subroutines differ in subtle
  2746. but significant ways. HandleError is only invoked at the point where
  2747. the DBI is about to return to the application with C<err> set true.
  2748. It's not invoked by the failure of a method that's been called by
  2749. another DBI method. HandleSetErr, on the other hand, is called
  2750. whenever set_err() is called with a defined C<err> value, even if false.
  2751. So it's not just for errors, despite the name, but also warn and info states.
  2752. The set_err() method, and thus HandleSetErr, may be called multiple
  2753. times within a method and is usually invoked from deep within driver code.
  2754. In theory a driver can use the return value from HandleSetErr via
  2755. set_err() to decide whether to continue or not. If set_err() returns
  2756. an empty list, indicating that the HandleSetErr code has 'handled'
  2757. the 'error', the driver could then continue instead of failing (if
  2758. that's a reasonable thing to do). This isn't excepted to be
  2759. common and any such cases should be clearly marked in the driver
  2760. documentation and discussed on the dbi-dev mailing list.
  2761. The C<HandleSetErr> attribute was added in DBI 1.41.
  2762. =item C<ErrCount> (unsigned integer)
  2763. The C<ErrCount> attribute is incremented whenever the set_err()
  2764. method records an error. It isn't incremented by warnings or
  2765. information states. It is not reset by the DBI at any time.
  2766. The C<ErrCount> attribute was added in DBI 1.41. Older drivers may
  2767. not have been updated to use set_err() to record errors and so this
  2768. attribute may not be incremented when using them.
  2769. =item C<ShowErrorStatement> (boolean, inherited)
  2770. The C<ShowErrorStatement> attribute can be used to cause the relevant
  2771. Statement text to be appended to the error messages generated by
  2772. the C<RaiseError>, C<PrintError>, and C<PrintWarn> attributes.
  2773. Only applies to errors on statement handles
  2774. plus the prepare(), do(), and the various C<select*()> database handle methods.
  2775. (The exact format of the appended text is subject to change.)
  2776. If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter
  2777. (placeholder) values then those are formatted and appended to the
  2778. end of the Statement text in the error message.
  2779. =item C<TraceLevel> (integer, inherited)
  2780. The C<TraceLevel> attribute can be used as an alternative to the
  2781. L</trace> method to set the DBI trace level and trace flags for a
  2782. specific handle. See L</TRACING> for more details.
  2783. The C<TraceLevel> attribute is especially useful combined with
  2784. C<local> to alter the trace settings for just a single block of code.
  2785. =item C<FetchHashKeyName> (string, inherited)
  2786. The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref()
  2787. method should perform case conversion on the field names used for
  2788. the hash keys. For historical reasons it defaults to 'C<NAME>' but
  2789. it is recommended to set it to 'C<NAME_lc>' (convert to lower case)
  2790. or 'C<NAME_uc>' (convert to upper case) according to your preference.
  2791. It can only be set for driver and database handles. For statement
  2792. handles the value is frozen when prepare() is called.
  2793. =item C<ChopBlanks> (boolean, inherited)
  2794. The C<ChopBlanks> attribute can be used to control the trimming of trailing space
  2795. characters from fixed width character (CHAR) fields. No other field
  2796. types are affected, even where field values have trailing spaces.
  2797. The default is false (although it is possible that the default may change).
  2798. Applications that need specific behaviour should set the attribute as
  2799. needed.
  2800. Drivers are not required to support this attribute, but any driver which
  2801. does not support it must arrange to return C<undef> as the attribute value.
  2802. =item C<LongReadLen> (unsigned integer, inherited)
  2803. The C<LongReadLen> attribute may be used to control the maximum
  2804. length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will
  2805. read from the database automatically when it fetches each row of data.
  2806. The C<LongReadLen> attribute only relates to fetching and reading
  2807. long values; it is not involved in inserting or updating them.
  2808. A value of 0 means not to automatically fetch any long data.
  2809. Drivers may return undef or an empty string for long fields when
  2810. C<LongReadLen> is 0.
  2811. The default is typically 0 (zero) bytes but may vary between drivers.
  2812. Applications fetching long fields should set this value to slightly
  2813. larger than the longest long field value to be fetched.
  2814. Some databases return some long types encoded as pairs of hex digits.
  2815. For these types, C<LongReadLen> relates to the underlying data
  2816. length and not the doubled-up length of the encoded string.
  2817. Changing the value of C<LongReadLen> for a statement handle after it
  2818. has been C<prepare>'d will typically have no effect, so it's common to
  2819. set C<LongReadLen> on the C<$dbh> before calling C<prepare>.
  2820. For most drivers the value used here has a direct effect on the
  2821. memory used by the statement handle while it's active, so don't be
  2822. too generous. If you can't be sure what value to use you could
  2823. execute an extra select statement to determine the longest value.
  2824. For example:
  2825. $dbh->{LongReadLen} = $dbh->selectrow_array(qq{
  2826. SELECT MAX(OCTET_LENGTH(long_column_name))
  2827. FROM table WHERE ...
  2828. });
  2829. $sth = $dbh->prepare(qq{
  2830. SELECT long_column_name, ... FROM table WHERE ...
  2831. });
  2832. You may need to take extra care if the table can be modified between
  2833. the first select and the second being executed. You may also need to
  2834. use a different function if OCTET_LENGTH() does not work for long
  2835. types in your database. For example, for Sybase use DATALENGTH() and
  2836. for Oracle use LENGTHB().
  2837. See also L</LongTruncOk> for information on truncation of long types.
  2838. =item C<LongTruncOk> (boolean, inherited)
  2839. The C<LongTruncOk> attribute may be used to control the effect of
  2840. fetching a long field value which has been truncated (typically
  2841. because it's longer than the value of the C<LongReadLen> attribute).
  2842. By default, C<LongTruncOk> is false and so fetching a long value that
  2843. needs to be truncated will cause the fetch to fail.
  2844. (Applications should always be sure to
  2845. check for errors after a fetch loop in case an error, such as a divide
  2846. by zero or long field truncation, caused the fetch to terminate
  2847. prematurely.)
  2848. If a fetch fails due to a long field truncation when C<LongTruncOk> is
  2849. false, many drivers will allow you to continue fetching further rows.
  2850. See also L</LongReadLen>.
  2851. =item C<TaintIn> (boolean, inherited)
  2852. If the C<TaintIn> attribute is set to a true value I<and> Perl is running in
  2853. taint mode (e.g., started with the C<-T> option), then all the arguments
  2854. to most DBI method calls are checked for being tainted. I<This may change.>
  2855. The attribute defaults to off, even if Perl is in taint mode.
  2856. See L<perlsec> for more about taint mode. If Perl is not
  2857. running in taint mode, this attribute has no effect.
  2858. When fetching data that you trust you can turn off the TaintIn attribute,
  2859. for that statement handle, for the duration of the fetch loop.
  2860. The C<TaintIn> attribute was added in DBI 1.31.
  2861. =item C<TaintOut> (boolean, inherited)
  2862. If the C<TaintOut> attribute is set to a true value I<and> Perl is running in
  2863. taint mode (e.g., started with the C<-T> option), then most data fetched
  2864. from the database is considered tainted. I<This may change.>
  2865. The attribute defaults to off, even if Perl is in taint mode.
  2866. See L<perlsec> for more about taint mode. If Perl is not
  2867. running in taint mode, this attribute has no effect.
  2868. When fetching data that you trust you can turn off the TaintOut attribute,
  2869. for that statement handle, for the duration of the fetch loop.
  2870. Currently only fetched data is tainted. It is possible that the results
  2871. of other DBI method calls, and the value of fetched attributes, may
  2872. also be tainted in future versions. That change may well break your
  2873. applications unless you take great care now. If you use DBI Taint mode,
  2874. please report your experience and any suggestions for changes.
  2875. The C<TaintOut> attribute was added in DBI 1.31.
  2876. =item C<Taint> (boolean, inherited)
  2877. The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present
  2878. for backwards compatibility).
  2879. Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving
  2880. it returns a true value if and only if L</TaintIn> and L</TaintOut> are
  2881. both set to true values.
  2882. =item C<Profile> (inherited)
  2883. The C<Profile> attribute enables the collection and reporting of method call timing statistics.
  2884. See the L<DBI::Profile> module documentation for I<much> more detail.
  2885. The C<Profile> attribute was added in DBI 1.24.
  2886. =item C<private_your_module_name_*>
  2887. The DBI provides a way to store extra information in a DBI handle as
  2888. "private" attributes. The DBI will allow you to store and retrieve any
  2889. attribute which has a name starting with "C<private_>".
  2890. It is I<strongly> recommended that you use just I<one> private
  2891. attribute (e.g., use a hash ref) I<and> give it a long and unambiguous
  2892. name that includes the module or application name that the attribute
  2893. relates to (e.g., "C<private_YourFullModuleName_thingy>").
  2894. Because of the way the Perl tie mechanism works you cannot reliably
  2895. use the C<||=> operator directly to initialise the attribute, like this:
  2896. my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG
  2897. you should use a two step approach like this:
  2898. my $foo = $dbh->{private_yourmodname_foo};
  2899. $foo ||= $dbh->{private_yourmodname_foo} = { ... };
  2900. This attribute is primarily of interest to people sub-classing DBI.
  2901. =back
  2902. =head1 DBI DATABASE HANDLE OBJECTS
  2903. This section covers the methods and attributes associated with
  2904. database handles.
  2905. =head2 Database Handle Methods
  2906. The following methods are specified for DBI database handles:
  2907. =over 4
  2908. =item C<clone>
  2909. $new_dbh = $dbh->clone();
  2910. $new_dbh = $dbh->clone(\%attr);
  2911. The C<clone> method duplicates the $dbh connection by connecting
  2912. with the same parameters ($dsn, $user, $password) as originally used.
  2913. The attributes for the cloned connect are the same as those used
  2914. for the original connect, with some other attribute merged over
  2915. them depending on the \%attr parameter.
  2916. If \%attr is given then the attributes it contains are merged into
  2917. the original attributes and override any with the same names.
  2918. Effectively the same as doing:
  2919. %attribues_used = ( %original_attributes, %attr );
  2920. If \%attr is not given then it defaults to a hash containing all
  2921. the attributes in the attribute cache of $dbh excluding any non-code
  2922. references, plus the main boolean attributes (RaiseError, PrintError,
  2923. AutoCommit, etc.). This behaviour is subject to change.
  2924. The clone method can be used even if the database handle is disconnected.
  2925. The C<clone> method was added in DBI 1.33. It is very new and likely
  2926. to change.
  2927. =item C<data_sources>
  2928. @ary = $dbh->data_sources();
  2929. @ary = $dbh->data_sources(\%attr);
  2930. Returns a list of data sources (databases) available via the $dbh
  2931. driver's data_sources() method, plus any extra data sources that
  2932. the driver can discover via the connected $dbh. Typically the extra
  2933. data sources are other databases managed by the same server process
  2934. that the $dbh is connected to.
  2935. Data sources are returned in a form suitable for passing to the
  2936. L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
  2937. The data_sources() method, for a $dbh, was added in DBI 1.38.
  2938. =item C<do>
  2939. $rows = $dbh->do($statement) or die $dbh->errstr;
  2940. $rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
  2941. $rows = $dbh->do($statement, \%attr, @bind_values) or die ...
  2942. Prepare and execute a single statement. Returns the number of rows
  2943. affected or C<undef> on error. A return value of C<-1> means the
  2944. number of rows is not known, not applicable, or not available.
  2945. This method is typically most useful for I<non>-C<SELECT> statements that
  2946. either cannot be prepared in advance (due to a limitation of the
  2947. driver) or do not need to be executed repeatedly. It should not
  2948. be used for C<SELECT> statements because it does not return a statement
  2949. handle (so you can't fetch any data).
  2950. The default C<do> method is logically similar to:
  2951. sub do {
  2952. my($dbh, $statement, $attr, @bind_values) = @_;
  2953. my $sth = $dbh->prepare($statement, $attr) or return undef;
  2954. $sth->execute(@bind_values) or return undef;
  2955. my $rows = $sth->rows;
  2956. ($rows == 0) ? "0E0" : $rows; # always return true if no error
  2957. }
  2958. For example:
  2959. my $rows_deleted = $dbh->do(q{
  2960. DELETE FROM table
  2961. WHERE status = ?
  2962. }, undef, 'DONE') or die $dbh->errstr;
  2963. Using placeholders and C<@bind_values> with the C<do> method can be
  2964. useful because it avoids the need to correctly quote any variables
  2965. in the C<$statement>. But if you'll be executing the statement many
  2966. times then it's more efficient to C<prepare> it once and call
  2967. C<execute> many times instead.
  2968. The C<q{...}> style quoting used in this example avoids clashing with
  2969. quotes that may be used in the SQL statement. Use the double-quote-like
  2970. C<qq{...}> operator if you want to interpolate variables into the string.
  2971. See L<perlop/"Quote and Quote-like Operators"> for more details.
  2972. =item C<last_insert_id>
  2973. $rv = $dbh->last_insert_id($catalog, $schema, $table, $field);
  2974. $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
  2975. Returns a value 'identifying' the row just inserted, if possible.
  2976. Typically this would be a value assigned by the database server
  2977. to a column with an I<auto_increment> or I<serial> type.
  2978. Returns undef if the driver does not support the method or can't
  2979. determine the value.
  2980. The $catalog, $schema, $table, and $field parameters may be required
  2981. for some drivers (see below). If you don't know the parameter values
  2982. and your driver does not need them, then use C<undef> for each.
  2983. There are several caveats to be aware of with this method if you want
  2984. to use it for portable applications:
  2985. B<*> For some drivers the value may only available immediately after
  2986. the insert statement has executed (e.g., mysql, Informix).
  2987. B<*> For some drivers the $catalog, $schema, $table, and $field parameters
  2988. are required (e.g., Pg), for others they are ignored (e.g., mysql).
  2989. B<*> Drivers may return an indeterminate value if no insert has
  2990. been performed yet.
  2991. B<*> For some drivers the value may only be available if placeholders
  2992. have I<not> been used (e.g., Sybase, MS SQL). In this case the value
  2993. returned would be from the last non-placeholder insert statement.
  2994. B<*> Some drivers may need driver-specific hints about how to get
  2995. the value. For example, being told the name of the database 'sequence'
  2996. object that holds the value. Any such hints are passed as driver-specific
  2997. attributes in the \%attr parameter.
  2998. B<*> If the underlying database offers nothing better, then some
  2999. drivers may attempt to implement this method by executing
  3000. "C<select max($field) from $table>". Drivers using any approach
  3001. like this should issue a warning if C<AutoCommit> is true because
  3002. it is generally unsafe - another process may have modified the table
  3003. between your insert and the select. For situations where you know
  3004. it is safe, such as when you have locked the table, you can silence
  3005. the warning by passing C<Warn> => 0 in \%attr.
  3006. B<*> If no insert has been performed yet, or the last insert failed,
  3007. then the value is implementation defined.
  3008. Given all the caveats above, it's clear that this method must be
  3009. used with care.
  3010. The C<last_insert_id> method was added in DBI 1.38.
  3011. =item C<selectrow_array>
  3012. @row_ary = $dbh->selectrow_array($statement);
  3013. @row_ary = $dbh->selectrow_array($statement, \%attr);
  3014. @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
  3015. This utility method combines L</prepare>, L</execute> and
  3016. L</fetchrow_array> into a single call. If called in a list context, it
  3017. returns the first row of data from the statement. The C<$statement>
  3018. parameter can be a previously prepared statement handle, in which case
  3019. the C<prepare> is skipped.
  3020. If any method fails, and L</RaiseError> is not set, C<selectrow_array>
  3021. will return an empty list.
  3022. If called in a scalar context for a statement handle that has more
  3023. than one column, it is undefined whether the driver will return
  3024. the value of the first column or the last. So don't do that.
  3025. Also, in a scalar context, an C<undef> is returned if there are no
  3026. more rows or if an error occurred. That C<undef> can't be distinguished
  3027. from an C<undef> returned because the first field value was NULL.
  3028. For these reasons you should exercise some caution if you use
  3029. C<selectrow_array> in a scalar context.
  3030. =item C<selectrow_arrayref>
  3031. $ary_ref = $dbh->selectrow_arrayref($statement);
  3032. $ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
  3033. $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
  3034. This utility method combines L</prepare>, L</execute> and
  3035. L</fetchrow_arrayref> into a single call. It returns the first row of
  3036. data from the statement. The C<$statement> parameter can be a previously
  3037. prepared statement handle, in which case the C<prepare> is skipped.
  3038. If any method fails, and L</RaiseError> is not set, C<selectrow_array>
  3039. will return undef.
  3040. =item C<selectrow_hashref>
  3041. $hash_ref = $dbh->selectrow_hashref($statement);
  3042. $hash_ref = $dbh->selectrow_hashref($statement, \%attr);
  3043. $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
  3044. This utility method combines L</prepare>, L</execute> and
  3045. L</fetchrow_hashref> into a single call. It returns the first row of
  3046. data from the statement. The C<$statement> parameter can be a previously
  3047. prepared statement handle, in which case the C<prepare> is skipped.
  3048. If any method fails, and L</RaiseError> is not set, C<selectrow_hashref>
  3049. will return undef.
  3050. =item C<selectall_arrayref>
  3051. $ary_ref = $dbh->selectall_arrayref($statement);
  3052. $ary_ref = $dbh->selectall_arrayref($statement, \%attr);
  3053. $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
  3054. This utility method combines L</prepare>, L</execute> and
  3055. L</fetchall_arrayref> into a single call. It returns a reference to an
  3056. array containing a reference to an array for each row of data fetched.
  3057. The C<$statement> parameter can be a previously prepared statement handle,
  3058. in which case the C<prepare> is skipped. This is recommended if the
  3059. statement is going to be executed many times.
  3060. If L</RaiseError> is not set and any method except C<fetchall_arrayref>
  3061. fails then C<selectall_arrayref> will return C<undef>; if
  3062. C<fetchall_arrayref> fails then it will return with whatever data
  3063. has been fetched thus far. You should check C<$sth-E<gt>err>
  3064. afterwards (or use the C<RaiseError> attribute) to discover if the data is
  3065. complete or was truncated due to an error.
  3066. The L</fetchall_arrayref> method called by C<selectall_arrayref>
  3067. supports a $max_rows parameter. You can specify a value for $max_rows
  3068. by including a 'C<MaxRows>' attribute in \%attr. In which case finish()
  3069. is called for you after fetchall_arrayref() returns.
  3070. The L</fetchall_arrayref> method called by C<selectall_arrayref>
  3071. also supports a $slice parameter. You can specify a value for $slice by
  3072. including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only
  3073. difference between the two is that if C<Slice> is not defined and
  3074. C<Columns> is an array ref, then the array is assumed to contain column
  3075. index values (which count from 1), rather than perl array index values.
  3076. In which case the array is copied and each value decremented before
  3077. passing to C</fetchall_arrayref>.
  3078. =item C<selectall_hashref>
  3079. $hash_ref = $dbh->selectall_hashref($statement, $key_field);
  3080. $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr);
  3081. $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values);
  3082. This utility method combines L</prepare>, L</execute> and
  3083. L</fetchall_hashref> into a single call. It returns a reference to a
  3084. hash containing one entry for each row. The key for each row entry is
  3085. specified by $key_field. The value is a reference to a hash returned by
  3086. C<fetchrow_hashref>.
  3087. The C<$statement> parameter can be a previously prepared statement handle,
  3088. in which case the C<prepare> is skipped. This is recommended if the
  3089. statement is going to be executed many times.
  3090. If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set,
  3091. C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and
  3092. L</RaiseError> is not set, then it will return with whatever data it
  3093. has fetched thus far. $DBI::err should be checked to catch that.
  3094. =item C<selectcol_arrayref>
  3095. $ary_ref = $dbh->selectcol_arrayref($statement);
  3096. $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
  3097. $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
  3098. This utility method combines L</prepare>, L</execute>, and fetching one
  3099. column from all the rows, into a single call. It returns a reference to
  3100. an array containing the values of the first column from each row.
  3101. The C<$statement> parameter can be a previously prepared statement handle,
  3102. in which case the C<prepare> is skipped. This is recommended if the
  3103. statement is going to be executed many times.
  3104. If any method except C<fetch> fails, and L</RaiseError> is not set,
  3105. C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and
  3106. L</RaiseError> is not set, then it will return with whatever data it
  3107. has fetched thus far. $DBI::err should be checked to catch that.
  3108. The C<selectcol_arrayref> method defaults to pushing a single column
  3109. value (the first) from each row into the result array. However, it can
  3110. also push another column, or even multiple columns per row, into the
  3111. result array. This behaviour can be specified via a 'C<Columns>'
  3112. attribute which must be a ref to an array containing the column number
  3113. or numbers to use. For example:
  3114. # get array of id and name pairs:
  3115. my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] });
  3116. my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name
  3117. You can specify a maximum number of rows to fetch by including a
  3118. 'C<MaxRows>' attribute in \%attr.
  3119. =item C<prepare>
  3120. $sth = $dbh->prepare($statement) or die $dbh->errstr;
  3121. $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr;
  3122. Prepares a statement for later execution by the database
  3123. engine and returns a reference to a statement handle object.
  3124. The returned statement handle can be used to get attributes of the
  3125. statement and invoke the L</execute> method. See L</Statement Handle Methods>.
  3126. Drivers for engines without the concept of preparing a
  3127. statement will typically just store the statement in the returned
  3128. handle and process it when C<$sth-E<gt>execute> is called. Such drivers are
  3129. unlikely to give much useful information about the
  3130. statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute>
  3131. has been called. Portable applications should take this into account.
  3132. In general, DBI drivers do not parse the contents of the statement
  3133. (other than simply counting any L</Placeholders>). The statement is
  3134. passed directly to the database engine, sometimes known as pass-thru
  3135. mode. This has advantages and disadvantages. On the plus side, you can
  3136. access all the functionality of the engine being used. On the downside,
  3137. you're limited if you're using a simple engine, and you need to take extra care if
  3138. writing applications intended to be portable between engines.
  3139. Portable applications should not assume that a new statement can be
  3140. prepared and/or executed while still fetching results from a previous
  3141. statement.
  3142. Some command-line SQL tools use statement terminators, like a semicolon,
  3143. to indicate the end of a statement. Such terminators should not normally
  3144. be used with the DBI.
  3145. =item C<prepare_cached>
  3146. $sth = $dbh->prepare_cached($statement)
  3147. $sth = $dbh->prepare_cached($statement, \%attr)
  3148. $sth = $dbh->prepare_cached($statement, \%attr, $if_active)
  3149. Like L</prepare> except that the statement handle returned will be
  3150. stored in a hash associated with the C<$dbh>. If another call is made to
  3151. C<prepare_cached> with the same C<$statement> and C<%attr> parameter values,
  3152. then the corresponding cached C<$sth> will be returned without contacting the
  3153. database server.
  3154. The C<$if_active> parameter lets you adjust the behaviour if an
  3155. already cached statement handle is still Active. There are several
  3156. alternatives:
  3157. =over 4
  3158. =item B<0>: A warning will be generated, and finish() will be called on
  3159. the statement handle before it is returned. This is the default
  3160. behaviour if $if_active is not passed.
  3161. =item B<1>: finish() will be called on the statement handle, but the
  3162. warning is suppressed.
  3163. =item B<2>: Disables any checking.
  3164. =item B<3>: The existing active statement handle will be removed from the
  3165. cache and a new statement handle prepared and cached in its place.
  3166. This is the safest option because it doesn't affect the state of the
  3167. old handle, it just removes it from the cache. [Added in DBI 1.40]
  3168. =back
  3169. Here are some examples of C<prepare_cached>:
  3170. sub insert_hash {
  3171. my ($table, $field_values) = @_;
  3172. my @fields = sort keys %$field_values; # sort required
  3173. my @values = @{$field_values}{@fields};
  3174. my $sql = sprintf "insert into %s (%s) values (%s)",
  3175. $table, join(",", @fields), join(",", ("?")x@fields);
  3176. my $sth = $dbh->prepare_cached($sql);
  3177. return $sth->execute(@values);
  3178. }
  3179. sub search_hash {
  3180. my ($table, $field_values) = @_;
  3181. my @fields = sort keys %$field_values; # sort required
  3182. my @values = @{$field_values}{@fields};
  3183. my $qualifier = "";
  3184. $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
  3185. $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
  3186. return $dbh->selectall_arrayref($sth, {}, @values);
  3187. }
  3188. I<Caveat emptor:> This caching can be useful in some applications,
  3189. but it can also cause problems and should be used with care. Here
  3190. is a contrived case where caching would cause a significant problem:
  3191. my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
  3192. $sth->execute(...);
  3193. while (my $data = $sth->fetchrow_hashref) {
  3194. # later, in some other code called within the loop...
  3195. my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
  3196. $sth2->execute(...);
  3197. while (my $data2 = $sth2->fetchrow_arrayref) {
  3198. do_stuff(...);
  3199. }
  3200. }
  3201. In this example, since both handles are preparing the exact same statement,
  3202. C<$sth2> will not be its own statement handle, but a duplicate of C<$sth>
  3203. returned from the cache. The results will certainly not be what you expect.
  3204. Typically the the inner fetch loop will work normally, fetching all
  3205. the records and terminating when there are no more, but now $sth
  3206. is the same as $sth2 the outer fetch loop will also terminate.
  3207. You'll know if you run into this problem because prepare_cached()
  3208. will generate a warning by default (when $if_active is false).
  3209. The cache used by prepare_cached() is keyed by both the statement
  3210. and any attributes so you can also avoid this issue by doing something
  3211. like:
  3212. $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ });
  3213. which will ensure that prepare_cached only returns statements cached
  3214. by that line of code in that source file.
  3215. =item C<commit>
  3216. $rc = $dbh->commit or die $dbh->errstr;
  3217. Commit (make permanent) the most recent series of database changes
  3218. if the database supports transactions and AutoCommit is off.
  3219. If C<AutoCommit> is on, then calling
  3220. C<commit> will issue a "commit ineffective with AutoCommit" warning.
  3221. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3222. =item C<rollback>
  3223. $rc = $dbh->rollback or die $dbh->errstr;
  3224. Rollback (undo) the most recent series of uncommitted database
  3225. changes if the database supports transactions and AutoCommit is off.
  3226. If C<AutoCommit> is on, then calling
  3227. C<rollback> will issue a "rollback ineffective with AutoCommit" warning.
  3228. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3229. =item C<begin_work>
  3230. $rc = $dbh->begin_work or die $dbh->errstr;
  3231. Enable transactions (by turning C<AutoCommit> off) until the next call
  3232. to C<commit> or C<rollback>. After the next C<commit> or C<rollback>,
  3233. C<AutoCommit> will automatically be turned on again.
  3234. If C<AutoCommit> is already off when C<begin_work> is called then
  3235. it does nothing except return an error. If the driver does not support
  3236. transactions then when C<begin_work> attempts to set C<AutoCommit> off
  3237. the driver will trigger a fatal error.
  3238. See also L</Transactions> in the L</FURTHER INFORMATION> section below.
  3239. =item C<disconnect>
  3240. $rc = $dbh->disconnect or warn $dbh->errstr;
  3241. Disconnects the database from the database handle. C<disconnect> is typically only used
  3242. before exiting the program. The handle is of little use after disconnecting.
  3243. The transaction behaviour of the C<disconnect> method is, sadly,
  3244. undefined. Some database systems (such as Oracle and Ingres) will
  3245. automatically commit any outstanding changes, but others (such as
  3246. Informix) will rollback any outstanding changes. Applications not
  3247. using C<AutoCommit> should explicitly call C<commit> or C<rollback> before
  3248. calling C<disconnect>.
  3249. The database is automatically disconnected by the C<DESTROY> method if
  3250. still connected when there are no longer any references to the handle.
  3251. The C<DESTROY> method for each driver should implicitly call C<rollback> to
  3252. undo any uncommitted changes. This is vital behaviour to ensure that
  3253. incomplete transactions don't get committed simply because Perl calls
  3254. C<DESTROY> on every object before exiting. Also, do not rely on the order
  3255. of object destruction during "global destruction", as it is undefined.
  3256. Generally, if you want your changes to be commited or rolled back when
  3257. you disconnect, then you should explicitly call L</commit> or L</rollback>
  3258. before disconnecting.
  3259. If you disconnect from a database while you still have active
  3260. statement handles (e.g., SELECT statement handles that may have
  3261. more data to fetch), you will get a warning. The warning may indicate
  3262. that a fetch loop terminated early, perhaps due to an uncaught error.
  3263. To avoid the warning call the C<finish> method on the active handles.
  3264. =item C<ping>
  3265. $rc = $dbh->ping;
  3266. Attempts to determine, in a reasonably efficient way, if the database
  3267. server is still running and the connection to it is still working.
  3268. Individual drivers should implement this function in the most suitable
  3269. manner for their database engine.
  3270. The current I<default> implementation always returns true without
  3271. actually doing anything. Actually, it returns "C<0 but true>" which is
  3272. true but zero. That way you can tell if the return value is genuine or
  3273. just the default. Drivers should override this method with one that
  3274. does the right thing for their type of database.
  3275. Few applications would have direct use for this method. See the specialized
  3276. Apache::DBI module for one example usage.
  3277. =item C<get_info>
  3278. $value = $dbh->get_info( $info_type );
  3279. Returns information about the implementation, i.e. driver and data
  3280. source capabilities, restrictions etc. It returns C<undef> for
  3281. unknown or unimplemented information types. For example:
  3282. $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER
  3283. $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
  3284. See L</"Standards Reference Information"> for more detailed information
  3285. about the information types and their meanings and possible return values.
  3286. The DBI::Const::GetInfoType module exports a %GetInfoType hash that
  3287. can be used to map info type names to numbers. For example:
  3288. $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
  3289. The names are a merging of the ANSI and ODBC standards (which differ
  3290. in some cases). See L<DBI::Const::GetInfoType> for more details.
  3291. Because some DBI methods make use of get_info(), drivers are strongly
  3292. encouraged to support I<at least> the following very minimal set
  3293. of information types to ensure the DBI itself works properly:
  3294. Type Name Example A Example B
  3295. ---- -------------------------- ------------ ----------------
  3296. 17 SQL_DBMS_NAME 'ACCESS' 'Oracle'
  3297. 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...'
  3298. 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"'
  3299. 41 SQL_CATALOG_NAME_SEPARATOR '.' '@'
  3300. 114 SQL_CATALOG_LOCATION 1 2
  3301. =item C<table_info>
  3302. $sth = $dbh->table_info( $catalog, $schema, $table, $type );
  3303. $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
  3304. Returns an active statement handle that can be used to fetch
  3305. information about tables and views that exist in the database.
  3306. The arguments $catalog, $schema and $table may accept search patterns
  3307. according to the database/driver, for example: $table = '%FOO%';
  3308. Remember that the underscore character ('C<_>') is a search pattern
  3309. that means match any character, so 'FOO_%' is the same as 'FOO%'
  3310. and 'FOO_BAR%' will match names like 'FOO1BAR'.
  3311. The value of $type is a comma-separated list of one or more types of
  3312. tables to be returned in the result set. Each value may optionally be
  3313. quoted, e.g.:
  3314. $type = "TABLE";
  3315. $type = "'TABLE','VIEW'";
  3316. In addition the following special cases may also be supported by some drivers:
  3317. =over 4
  3318. =item *
  3319. If the value of $catalog is '%' and $schema and $table name
  3320. are empty strings, the result set contains a list of catalog names.
  3321. For example:
  3322. $sth = $dbh->table_info('%', '', '');
  3323. =item *
  3324. If the value of $schema is '%' and $catalog and $table are empty
  3325. strings, the result set contains a list of schema names.
  3326. =item *
  3327. If the value of $type is '%' and $catalog, $schema, and $table are all
  3328. empty strings, the result set contains a list of table types.
  3329. =back
  3330. If your driver doesn't support one or more of the selection filter
  3331. parameters then you may get back more than you asked for and can
  3332. do the filtering yourself.
  3333. This method can be expensive, and can return a large amount of data.
  3334. (For example, small Oracle installation returns over 2000 rows.)
  3335. So it's a good idea to use the filters to limit the data as much as possible.
  3336. The statement handle returned has at least the following fields in the
  3337. order show below. Other fields, after these, may also be present.
  3338. B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not
  3339. applicable to the data source, which is usually the case. This field
  3340. is empty if not applicable to the table.
  3341. B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value.
  3342. This field is NULL (C<undef>) if not applicable to data source, and
  3343. empty if not applicable to the table.
  3344. B<TABLE_NAME>: Name of the table (or view, synonym, etc).
  3345. B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE",
  3346. "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type
  3347. identifier that is specific to the data
  3348. source.
  3349. B<REMARKS>: A description of the table. May be NULL (C<undef>).
  3350. Note that C<table_info> might not return records for all tables.
  3351. Applications can use any valid table regardless of whether it's
  3352. returned by C<table_info>.
  3353. See also L</tables>, L</"Catalog Methods"> and
  3354. L</"Standards Reference Information">.
  3355. =item C<column_info>
  3356. $sth = $dbh->column_info( $catalog, $schema, $table, $column );
  3357. Returns an active statement handle that can be used to fetch
  3358. information about columns in specified tables.
  3359. The arguments $schema, $table and $column may accept search patterns
  3360. according to the database/driver, for example: $table = '%FOO%';
  3361. Note: The support for the selection criteria is driver specific. If the
  3362. driver doesn't support one or more of them then you may get back more
  3363. than you asked for and can do the filtering yourself.
  3364. The statement handle returned has at least the following fields in the
  3365. order shown below. Other fields, after these, may also be present.
  3366. B<TABLE_CAT>: The catalog identifier.
  3367. This field is NULL (C<undef>) if not applicable to the data source,
  3368. which is often the case. This field is empty if not applicable to the
  3369. table.
  3370. B<TABLE_SCHEM>: The schema identifier.
  3371. This field is NULL (C<undef>) if not applicable to the data source,
  3372. and empty if not applicable to the table.
  3373. B<TABLE_NAME>: The table identifier.
  3374. Note: A driver may provide column metadata not only for base tables, but
  3375. also for derived objects like SYNONYMS etc.
  3376. B<COLUMN_NAME>: The column identifier.
  3377. B<DATA_TYPE>: The concise data type code.
  3378. B<TYPE_NAME>: A data source dependent data type name.
  3379. B<COLUMN_SIZE>: The column size.
  3380. This is the maximum length in characters for character data types,
  3381. the number of digits or bits for numeric data types or the length
  3382. in the representation of temporal types.
  3383. See the relevant specifications for detailed information.
  3384. B<BUFFER_LENGTH>: The length in bytes of transferred data.
  3385. B<DECIMAL_DIGITS>: The total number of significant digits to the right of
  3386. the decimal point.
  3387. B<NUM_PREC_RADIX>: The radix for numeric precision.
  3388. The value is 10 or 2 for numeric data types and NULL (C<undef>) if not
  3389. applicable.
  3390. B<NULLABLE>: Indicates if a column can accept NULLs.
  3391. The following values are defined:
  3392. SQL_NO_NULLS 0
  3393. SQL_NULLABLE 1
  3394. SQL_NULLABLE_UNKNOWN 2
  3395. B<REMARKS>: A description of the column.
  3396. B<COLUMN_DEF>: The default value of the column.
  3397. B<SQL_DATA_TYPE>: The SQL data type.
  3398. B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types.
  3399. B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary
  3400. data type column.
  3401. B<ORDINAL_POSITION>: The column sequence number (starting with 1).
  3402. B<IS_NULLABLE>: Indicates if the column can accept NULLs.
  3403. Possible values are: 'NO', 'YES' and ''.
  3404. SQL/CLI defines the following additional columns:
  3405. CHAR_SET_CAT
  3406. CHAR_SET_SCHEM
  3407. CHAR_SET_NAME
  3408. COLLATION_CAT
  3409. COLLATION_SCHEM
  3410. COLLATION_NAME
  3411. UDT_CAT
  3412. UDT_SCHEM
  3413. UDT_NAME
  3414. DOMAIN_CAT
  3415. DOMAIN_SCHEM
  3416. DOMAIN_NAME
  3417. SCOPE_CAT
  3418. SCOPE_SCHEM
  3419. SCOPE_NAME
  3420. MAX_CARDINALITY
  3421. DTD_IDENTIFIER
  3422. IS_SELF_REF
  3423. Drivers capable of supplying any of those values should do so in
  3424. the corresponding column and supply undef values for the others.
  3425. Drivers wishing to provide extra database/driver specific information
  3426. should do so in extra columns beyond all those listed above, and
  3427. use lowercase field names with the driver-specific prefix (i.e.,
  3428. 'ora_...'). Applications accessing such fields should do so by name
  3429. and not by column number.
  3430. The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME
  3431. and ORDINAL_POSITION.
  3432. Note: There is some overlap with statement attributes (in perl) and
  3433. SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
  3434. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3435. =item C<primary_key_info>
  3436. $sth = $dbh->primary_key_info( $catalog, $schema, $table );
  3437. Returns an active statement handle that can be used to fetch information
  3438. about columns that make up the primary key for a table.
  3439. The arguments don't accept search patterns (unlike table_info()).
  3440. For example:
  3441. $sth = $dbh->primary_key_info( undef, $user, 'foo' );
  3442. $data = $sth->fetchall_arrayref;
  3443. The statement handle will return one row per column, ordered by
  3444. TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ.
  3445. If there is no primary key then the statement handle will fetch no rows.
  3446. Note: The support for the selection criteria, such as $catalog, is
  3447. driver specific. If the driver doesn't support catalogs and/or
  3448. schemas, it may ignore these criteria.
  3449. The statement handle returned has at least the following fields in the
  3450. order shown below. Other fields, after these, may also be present.
  3451. B<TABLE_CAT>: The catalog identifier.
  3452. This field is NULL (C<undef>) if not applicable to the data source,
  3453. which is often the case. This field is empty if not applicable to the
  3454. table.
  3455. B<TABLE_SCHEM>: The schema identifier.
  3456. This field is NULL (C<undef>) if not applicable to the data source,
  3457. and empty if not applicable to the table.
  3458. B<TABLE_NAME>: The table identifier.
  3459. B<COLUMN_NAME>: The column identifier.
  3460. B<KEY_SEQ>: The column sequence number (starting with 1).
  3461. Note: This field is named B<ORDINAL_POSITION> in SQL/CLI.
  3462. B<PK_NAME>: The primary key constraint identifier.
  3463. This field is NULL (C<undef>) if not applicable to the data source.
  3464. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3465. =item C<primary_key>
  3466. @key_column_names = $dbh->primary_key( $catalog, $schema, $table );
  3467. Simple interface to the primary_key_info() method. Returns a list of
  3468. the column names that comprise the primary key of the specified table.
  3469. The list is in primary key column sequence order.
  3470. If there is no primary key then an empty list is returned.
  3471. =item C<foreign_key_info>
  3472. $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
  3473. , $fk_catalog, $fk_schema, $fk_table );
  3474. $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
  3475. , $fk_catalog, $fk_schema, $fk_table
  3476. , \%attr );
  3477. Returns an active statement handle that can be used to fetch information
  3478. about foreign keys in and/or referencing the specified table(s).
  3479. The arguments don't accept search patterns (unlike table_info()).
  3480. C<$pk_catalog>, C<$pk_schema>, C<$pk_table>
  3481. identify the primary (unique) key table (B<PKT>).
  3482. C<$fk_catalog>, C<$fk_schema>, C<$fk_table>
  3483. identify the foreign key table (B<FKT>).
  3484. If both B<PKT> and B<FKT> are given, the function returns the foreign key, if
  3485. any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>.
  3486. (Note: In SQL/CLI, the result is implementation-defined.)
  3487. If only B<PKT> is given, then the result set contains the primary key
  3488. of that table and all foreign keys that refer to it.
  3489. If only B<FKT> is given, then the result set contains all foreign keys
  3490. in that table and the primary keys to which they refer.
  3491. (Note: In SQL/CLI, the result includes unique keys too.)
  3492. For example:
  3493. $sth = $dbh->foreign_key_info( undef, $user, 'master');
  3494. $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail');
  3495. $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail');
  3496. Note: The support for the selection criteria, such as C<$catalog>, is
  3497. driver specific. If the driver doesn't support catalogs and/or
  3498. schemas, it may ignore these criteria.
  3499. The statement handle returned has the following fields in the order shown below.
  3500. Because ODBC never includes unique keys, they define different columns in the
  3501. result set than SQL/CLI. SQL/CLI column names are shown in parentheses.
  3502. B<PKTABLE_CAT ( UK_TABLE_CAT )>:
  3503. The primary (unique) key table catalog identifier.
  3504. This field is NULL (C<undef>) if not applicable to the data source,
  3505. which is often the case. This field is empty if not applicable to the
  3506. table.
  3507. B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>:
  3508. The primary (unique) key table schema identifier.
  3509. This field is NULL (C<undef>) if not applicable to the data source,
  3510. and empty if not applicable to the table.
  3511. B<PKTABLE_NAME ( UK_TABLE_NAME )>:
  3512. The primary (unique) key table identifier.
  3513. B<PKCOLUMN_NAME (UK_COLUMN_NAME )>:
  3514. The primary (unique) key column identifier.
  3515. B<FKTABLE_CAT ( FK_TABLE_CAT )>:
  3516. The foreign key table catalog identifier.
  3517. This field is NULL (C<undef>) if not applicable to the data source,
  3518. which is often the case. This field is empty if not applicable to the
  3519. table.
  3520. B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>:
  3521. The foreign key table schema identifier.
  3522. This field is NULL (C<undef>) if not applicable to the data source,
  3523. and empty if not applicable to the table.
  3524. B<FKTABLE_NAME ( FK_TABLE_NAME )>:
  3525. The foreign key table identifier.
  3526. B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>:
  3527. The foreign key column identifier.
  3528. B<KEY_SEQ ( ORDINAL_POSITION )>:
  3529. The column sequence number (starting with 1).
  3530. B<UPDATE_RULE ( UPDATE_RULE )>:
  3531. The referential action for the UPDATE rule.
  3532. The following codes are defined:
  3533. CASCADE 0
  3534. RESTRICT 1
  3535. SET NULL 2
  3536. NO ACTION 3
  3537. SET DEFAULT 4
  3538. B<DELETE_RULE ( DELETE_RULE )>:
  3539. The referential action for the DELETE rule.
  3540. The codes are the same as for UPDATE_RULE.
  3541. B<FK_NAME ( FK_NAME )>:
  3542. The foreign key name.
  3543. B<PK_NAME ( UK_NAME )>:
  3544. The primary (unique) key name.
  3545. B<DEFERRABILITY ( DEFERABILITY )>:
  3546. The deferrability of the foreign key constraint.
  3547. The following codes are defined:
  3548. INITIALLY DEFERRED 5
  3549. INITIALLY IMMEDIATE 6
  3550. NOT DEFERRABLE 7
  3551. B< ( UNIQUE_OR_PRIMARY )>:
  3552. This column is necessary if a driver includes all candidate (i.e. primary and
  3553. alternate) keys in the result set (as specified by SQL/CLI).
  3554. The value of this column is UNIQUE if the foreign key references an alternate
  3555. key and PRIMARY if the foreign key references a primary key, or it
  3556. may be undefined if the driver doesn't have access to the information.
  3557. See also L</"Catalog Methods"> and L</"Standards Reference Information">.
  3558. =item C<tables>
  3559. @names = $dbh->tables( $catalog, $schema, $table, $type );
  3560. @names = $dbh->tables; # deprecated
  3561. Simple interface to table_info(). Returns a list of matching
  3562. table names, possibly including a catalog/schema prefix.
  3563. See L</table_info> for a description of the parameters.
  3564. If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR)
  3565. then the table names are constructed and quoted by L</quote_identifier>
  3566. to ensure they are usable even if they contain whitespace or reserved
  3567. words etc. This means that the table names returned will include
  3568. quote characters.
  3569. =item C<type_info_all>
  3570. $type_info_all = $dbh->type_info_all;
  3571. Returns a reference to an array which holds information about each data
  3572. type variant supported by the database and driver. The array and its
  3573. contents should be treated as read-only.
  3574. The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs.
  3575. The items following that are references to arrays, one per supported data
  3576. type variant. The leading index hash defines the names and order of the
  3577. fields within the arrays that follow it.
  3578. For example:
  3579. $type_info_all = [
  3580. { TYPE_NAME => 0,
  3581. DATA_TYPE => 1,
  3582. COLUMN_SIZE => 2, # was PRECISION originally
  3583. LITERAL_PREFIX => 3,
  3584. LITERAL_SUFFIX => 4,
  3585. CREATE_PARAMS => 5,
  3586. NULLABLE => 6,
  3587. CASE_SENSITIVE => 7,
  3588. SEARCHABLE => 8,
  3589. UNSIGNED_ATTRIBUTE=> 9,
  3590. FIXED_PREC_SCALE => 10, # was MONEY originally
  3591. AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
  3592. LOCAL_TYPE_NAME => 12,
  3593. MINIMUM_SCALE => 13,
  3594. MAXIMUM_SCALE => 14,
  3595. SQL_DATA_TYPE => 15,
  3596. SQL_DATETIME_SUB => 16,
  3597. NUM_PREC_RADIX => 17,
  3598. INTERVAL_PRECISION=> 18,
  3599. },
  3600. [ 'VARCHAR', SQL_VARCHAR,
  3601. undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
  3602. ],
  3603. [ 'INTEGER', SQL_INTEGER,
  3604. undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
  3605. ],
  3606. ];
  3607. More than one row may have the same value in the C<DATA_TYPE>
  3608. field if there are different ways to spell the type name and/or there
  3609. are variants of the type with different attributes (e.g., with and
  3610. without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc).
  3611. The rows are ordered by C<DATA_TYPE> first and then by how closely each
  3612. type maps to the corresponding ODBC SQL data type, closest first.
  3613. The meaning of the fields is described in the documentation for
  3614. the L</type_info> method.
  3615. An 'index' hash is provided so you don't need to rely on index
  3616. values defined above. However, using DBD::ODBC with some old ODBC
  3617. drivers may return older names, shown as comments in the example above.
  3618. Another issue with the index hash is that the lettercase of the
  3619. keys is not defined. It is usually uppercase, as show here, but
  3620. drivers may return names with any lettercase.
  3621. Drivers are also free to return extra driver-specific columns of
  3622. information - though it's recommended that they start at column
  3623. index 50 to leave room for expansion of the DBI/ODBC specification.
  3624. The type_info_all() method is not normally used directly.
  3625. The L</type_info> method provides a more usable and useful interface
  3626. to the data.
  3627. =item C<type_info>
  3628. @type_info = $dbh->type_info($data_type);
  3629. Returns a list of hash references holding information about one or more
  3630. variants of $data_type. The list is ordered by C<DATA_TYPE> first and
  3631. then by how closely each type maps to the corresponding ODBC SQL data
  3632. type, closest first. If called in a scalar context then only the first
  3633. (best) element is returned.
  3634. If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will
  3635. contain hashes for all data type variants supported by the database and driver.
  3636. If $data_type is an array reference then C<type_info> returns the
  3637. information for the I<first> type in the array that has any matches.
  3638. The keys of the hash follow the same letter case conventions as the
  3639. rest of the DBI (see L</Naming Conventions and Name Space>). The
  3640. following uppercase items should always exist, though may be undef:
  3641. =over 4
  3642. =item TYPE_NAME (string)
  3643. Data type name for use in CREATE TABLE statements etc.
  3644. =item DATA_TYPE (integer)
  3645. SQL data type number.
  3646. =item COLUMN_SIZE (integer)
  3647. For numeric types, this is either the total number of digits (if the
  3648. NUM_PREC_RADIX value is 10) or the total number of bits allowed in the
  3649. column (if NUM_PREC_RADIX is 2).
  3650. For string types, this is the maximum size of the string in characters.
  3651. For date and interval types, this is the maximum number of characters
  3652. needed to display the value.
  3653. =item LITERAL_PREFIX (string)
  3654. Characters used to prefix a literal. A typical prefix is "C<'>" for characters,
  3655. or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is
  3656. returned for data types for which this is not applicable.
  3657. =item LITERAL_SUFFIX (string)
  3658. Characters used to suffix a literal. Typically "C<'>" for characters.
  3659. NULL (C<undef>) is returned for data types where this is not applicable.
  3660. =item CREATE_PARAMS (string)
  3661. Parameter names for data type definition. For example, C<CREATE_PARAMS> for a
  3662. C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be
  3663. declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale>
  3664. are integer values. For a C<VARCHAR> it would be "C<max length>".
  3665. NULL (C<undef>) is returned for data types for which this is not applicable.
  3666. =item NULLABLE (integer)
  3667. Indicates whether the data type accepts a NULL value:
  3668. C<0> or an empty string = no, C<1> = yes, C<2> = unknown.
  3669. =item CASE_SENSITIVE (boolean)
  3670. Indicates whether the data type is case sensitive in collations and
  3671. comparisons.
  3672. =item SEARCHABLE (integer)
  3673. Indicates how the data type can be used in a WHERE clause, as
  3674. follows:
  3675. 0 - Cannot be used in a WHERE clause
  3676. 1 - Only with a LIKE predicate
  3677. 2 - All comparison operators except LIKE
  3678. 3 - Can be used in a WHERE clause with any comparison operator
  3679. =item UNSIGNED_ATTRIBUTE (boolean)
  3680. Indicates whether the data type is unsigned. NULL (C<undef>) is returned
  3681. for data types for which this is not applicable.
  3682. =item FIXED_PREC_SCALE (boolean)
  3683. Indicates whether the data type always has the same precision and scale
  3684. (such as a money type). NULL (C<undef>) is returned for data types
  3685. for which
  3686. this is not applicable.
  3687. =item AUTO_UNIQUE_VALUE (boolean)
  3688. Indicates whether a column of this data type is automatically set to a
  3689. unique value whenever a new row is inserted. NULL (C<undef>) is returned
  3690. for data types for which this is not applicable.
  3691. =item LOCAL_TYPE_NAME (string)
  3692. Localized version of the C<TYPE_NAME> for use in dialog with users.
  3693. NULL (C<undef>) is returned if a localized name is not available (in which
  3694. case C<TYPE_NAME> should be used).
  3695. =item MINIMUM_SCALE (integer)
  3696. The minimum scale of the data type. If a data type has a fixed scale,
  3697. then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
  3698. data types for which this is not applicable.
  3699. =item MAXIMUM_SCALE (integer)
  3700. The maximum scale of the data type. If a data type has a fixed scale,
  3701. then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
  3702. data types for which this is not applicable.
  3703. =item SQL_DATA_TYPE (integer)
  3704. This column is the same as the C<DATA_TYPE> column, except for interval
  3705. and datetime data types. For interval and datetime data types, the
  3706. C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the
  3707. C<SQL_DATETIME_SUB> field below will return the subcode for the specific
  3708. interval or datetime data type. If this field is NULL, then the driver
  3709. does not support or report on interval or datetime subtypes.
  3710. =item SQL_DATETIME_SUB (integer)
  3711. For interval or datetime data types, where the C<SQL_DATA_TYPE>
  3712. field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will
  3713. hold the I<subcode> for the specific interval or datetime data type.
  3714. Otherwise it will be NULL (C<undef>).
  3715. Although not mentioned explicitly in the standards, it seems there
  3716. is a simple relationship between these values:
  3717. DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
  3718. =item NUM_PREC_RADIX (integer)
  3719. The radix value of the data type. For approximate numeric types,
  3720. C<NUM_PREC_RADIX>
  3721. contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For
  3722. exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds
  3723. the number of decimal digits. NULL (C<undef>) is returned either for data types
  3724. for which this is not applicable or if the driver cannot report this information.
  3725. =item INTERVAL_PRECISION (integer)
  3726. The interval leading precision for interval types. NULL is returned
  3727. either for data types for which this is not applicable or if the driver
  3728. cannot report this information.
  3729. =back
  3730. For example, to find the type name for the fields in a select statement
  3731. you can do:
  3732. @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
  3733. Since DBI and ODBC drivers vary in how they map their types into the
  3734. ISO standard types you may need to search for more than one type.
  3735. Here's an example looking for a usable type to store a date:
  3736. $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
  3737. Similarly, to more reliably find a type to store small integers, you could
  3738. use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc.
  3739. See also L</"Standards Reference Information">.
  3740. =item C<quote>
  3741. $sql = $dbh->quote($value);
  3742. $sql = $dbh->quote($value, $data_type);
  3743. Quote a string literal for use as a literal value in an SQL statement,
  3744. by escaping any special characters (such as quotation marks)
  3745. contained within the string and adding the required type of outer
  3746. quotation marks.
  3747. $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
  3748. $dbh->quote("Don't");
  3749. For most database types, quote would return C<'Don''t'> (including the
  3750. outer quotation marks).
  3751. An undefined C<$value> value will be returned as the string C<NULL> (without
  3752. single quotation marks) to match how NULLs are represented in SQL.
  3753. If C<$data_type> is supplied, it is used to try to determine the required
  3754. quoting behaviour by using the information returned by L</type_info>.
  3755. As a special case, the standard numeric types are optimized to return
  3756. C<$value> without calling C<type_info>.
  3757. Quote will probably I<not> be able to deal with all possible input
  3758. (such as binary data or data containing newlines), and is not related in
  3759. any way with escaping or quoting shell meta-characters.
  3760. It is valid for the quote() method to return an SQL expression that
  3761. evaluates to the desired string. For example:
  3762. $quoted = $dbh->quote("one\ntwo\0three")
  3763. may return something like:
  3764. CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
  3765. The quote() method should I<not> be used with L</"Placeholders and
  3766. Bind Values">.
  3767. =item C<quote_identifier>
  3768. $sql = $dbh->quote_identifier( $name );
  3769. $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr );
  3770. Quote an identifier (table name etc.) for use in an SQL statement,
  3771. by escaping any special characters (such as double quotation marks)
  3772. it contains and adding the required type of outer quotation marks.
  3773. Undefined names are ignored and the remainder are quoted and then
  3774. joined together, typically with a dot (C<.>) character. For example:
  3775. $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' );
  3776. would, for most database types, return C<"Her schema"."My table">
  3777. (including all the double quotation marks).
  3778. If three names are supplied then the first is assumed to be a
  3779. catalog name and special rules may be applied based on what L</get_info>
  3780. returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114).
  3781. For example, for Oracle:
  3782. $id = $dbh->quote_identifier( 'link', 'schema', 'table' );
  3783. would return C<"schema"."table"@"link">.
  3784. =item C<take_imp_data>
  3785. $imp_data = $dbh->take_imp_data;
  3786. Leaves the $dbh in an almost dead, zombie-like, state and returns
  3787. a binary string of raw implementation data from the driver which
  3788. describes the current database connection. Effectively it detaches
  3789. the underlying database API connection data from the DBI handle.
  3790. After calling take_imp_data(), all other methods except C<DESTROY>
  3791. will generate a warning and return undef.
  3792. Why would you want to do this? You don't, forget I even mentioned it.
  3793. Unless, that is, you're implementing something advanced like a
  3794. multi-threaded connection pool.
  3795. The returned $imp_data can be passed as a C<dbi_imp_data> attribute
  3796. to a later connect() call, even in a separate thread in the same
  3797. process, where the driver can use it to 'adopt' the existing
  3798. connection that the implementation data was taken from.
  3799. Some things to keep in mind...
  3800. B<*> the $imp_data holds the only reference to the underlying
  3801. database API connection data. That connection is still 'live' and
  3802. won't be cleaned up properly unless the $imp_data is used to create
  3803. a new $dbh which can then disconnect() normally.
  3804. B<*> using the same $imp_data to create more than one other new
  3805. $dbh at a time may well lead to unpleasant problems. Don't do that.
  3806. The C<take_imp_data> method was added in DBI 1.36.
  3807. =back
  3808. =head2 Database Handle Attributes
  3809. This section describes attributes specific to database handles.
  3810. Changes to these database handle attributes do not affect any other
  3811. existing or future database handles.
  3812. Attempting to set or get the value of an unknown attribute generates a warning,
  3813. except for private driver-specific attributes (which all have names
  3814. starting with a lowercase letter).
  3815. Example:
  3816. $h->{AutoCommit} = ...; # set/write
  3817. ... = $h->{AutoCommit}; # get/read
  3818. =over 4
  3819. =item C<AutoCommit> (boolean)
  3820. If true, then database changes cannot be rolled-back (undone). If false,
  3821. then database changes automatically occur within a "transaction", which
  3822. must either be committed or rolled back using the C<commit> or C<rollback>
  3823. methods.
  3824. Drivers should always default to C<AutoCommit> mode (an unfortunate
  3825. choice largely forced on the DBI by ODBC and JDBC conventions.)
  3826. Attempting to set C<AutoCommit> to an unsupported value is a fatal error.
  3827. This is an important feature of the DBI. Applications that need
  3828. full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or
  3829. set C<AutoCommit> to 0 via L</connect>)
  3830. without having to check that the value was assigned successfully.
  3831. For the purposes of this description, we can divide databases into three
  3832. categories:
  3833. Databases which don't support transactions at all.
  3834. Databases in which a transaction is always active.
  3835. Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
  3836. B<* Databases which don't support transactions at all>
  3837. For these databases, attempting to turn C<AutoCommit> off is a fatal error.
  3838. C<commit> and C<rollback> both issue warnings about being ineffective while
  3839. C<AutoCommit> is in effect.
  3840. B<* Databases in which a transaction is always active>
  3841. These are typically mainstream commercial relational databases with
  3842. "ANSI standard" transaction behaviour.
  3843. If C<AutoCommit> is off, then changes to the database won't have any
  3844. lasting effect unless L</commit> is called (but see also
  3845. L</disconnect>). If L</rollback> is called then any changes since the
  3846. last commit are undone.
  3847. If C<AutoCommit> is on, then the effect is the same as if the DBI
  3848. called C<commit> automatically after every successful database
  3849. operation. So calling C<commit> or C<rollback> explicitly while
  3850. C<AutoCommit> is on would be ineffective because the changes would
  3851. have already been commited.
  3852. Changing C<AutoCommit> from off to on will trigger a L</commit>.
  3853. For databases which don't support a specific auto-commit mode, the
  3854. driver has to commit each statement automatically using an explicit
  3855. C<COMMIT> after it completes successfully (and roll it back using an
  3856. explicit C<ROLLBACK> if it fails). The error information reported to the
  3857. application will correspond to the statement which was executed, unless
  3858. it succeeded and the commit or rollback failed.
  3859. B<* Databases in which a transaction must be explicitly started>
  3860. For these databases, the intention is to have them act like databases in
  3861. which a transaction is always active (as described above).
  3862. To do this, the driver will automatically begin an explicit transaction
  3863. when C<AutoCommit> is turned off, or after a L</commit> or
  3864. L</rollback> (or when the application issues the next database
  3865. operation after one of those events).
  3866. In this way, the application does not have to treat these databases
  3867. as a special case.
  3868. See L</commit>, L</disconnect> and L</Transactions> for other important
  3869. notes about transactions.
  3870. =item C<Driver> (handle)
  3871. Holds the handle of the parent driver. The only recommended use for this
  3872. is to find the name of the driver using:
  3873. $dbh->{Driver}->{Name}
  3874. =item C<Name> (string)
  3875. Holds the "name" of the database. Usually (and recommended to be) the
  3876. same as the "C<dbi:DriverName:...>" string used to connect to the database,
  3877. but with the leading "C<dbi:DriverName:>" removed.
  3878. =item C<Statement> (string, read-only)
  3879. Returns the statement string passed to the most recent L</prepare> method
  3880. called in this database handle, even if that method failed. This is especially
  3881. useful where C<RaiseError> is enabled and the exception handler checks $@
  3882. and sees that a 'prepare' method call failed.
  3883. =item C<RowCacheSize> (integer)
  3884. A hint to the driver indicating the size of the local row cache that the
  3885. application would like the driver to use for future C<SELECT> statements.
  3886. If a row cache is not implemented, then setting C<RowCacheSize> is ignored
  3887. and getting the value returns C<undef>.
  3888. Some C<RowCacheSize> values have special meaning, as follows:
  3889. 0 - Automatically determine a reasonable cache size for each C<SELECT>
  3890. 1 - Disable the local row cache
  3891. >1 - Cache this many rows
  3892. <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
  3893. Note that large cache sizes may require a very large amount of memory
  3894. (I<cached rows * maximum size of row>). Also, a large cache will cause
  3895. a longer delay not only for the first fetch, but also whenever the
  3896. cache needs refilling.
  3897. See also the L</RowsInCache> statement handle attribute.
  3898. =item C<Username> (string)
  3899. Returns the username used to connect to the database.
  3900. =back
  3901. =head1 DBI STATEMENT HANDLE OBJECTS
  3902. This section lists the methods and attributes associated with DBI
  3903. statement handles.
  3904. =head2 Statement Handle Methods
  3905. The DBI defines the following methods for use on DBI statement handles:
  3906. =over 4
  3907. =item C<bind_param>
  3908. $sth->bind_param($p_num, $bind_value)
  3909. $sth->bind_param($p_num, $bind_value, \%attr)
  3910. $sth->bind_param($p_num, $bind_value, $bind_type)
  3911. The C<bind_param> method takes a copy of $bind_value and associates it
  3912. (binds it) with a placeholder, identified by $p_num, embedded in
  3913. the prepared statement. Placeholders are indicated with question
  3914. mark character (C<?>). For example:
  3915. $dbh->{RaiseError} = 1; # save having to check each method call
  3916. $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
  3917. $sth->bind_param(1, "John%"); # placeholders are numbered from 1
  3918. $sth->execute;
  3919. DBI::dump_results($sth);
  3920. See L</"Placeholders and Bind Values"> for more information.
  3921. B<Data Types for Placeholders>
  3922. The C<\%attr> parameter can be used to hint at the data type the
  3923. placeholder should have. Typically, the driver is only interested in
  3924. knowing if the placeholder should be bound as a number or a string.
  3925. $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
  3926. As a short-cut for the common case, the data type can be passed
  3927. directly, in place of the C<\%attr> hash reference. This example is
  3928. equivalent to the one above:
  3929. $sth->bind_param(1, $value, SQL_INTEGER);
  3930. The C<TYPE> value indicates the standard (non-driver-specific) type for
  3931. this parameter. To specify the driver-specific type, the driver may
  3932. support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>.
  3933. The SQL_INTEGER and other related constants can be imported using
  3934. use DBI qw(:sql_types);
  3935. See L</"DBI Constants"> for more information.
  3936. The data type for a placeholder cannot be changed after the first
  3937. C<bind_param> call. In fact the whole \%attr parameter is 'sticky'
  3938. in the sense that a driver only needs to consider the \%attr parameter
  3939. for the first call, for a given $sth and parameter. After that the driver
  3940. may ignore the \%attr parameter for that placeholder.
  3941. Perl only has string and number scalar data types. All database types
  3942. that aren't numbers are bound as strings and must be in a format the
  3943. database will understand except where the bind_param() TYPE attribute
  3944. specifies a type that implies a particular format. For example, given:
  3945. $sth->bind_param(1, $value, SQL_DATETIME);
  3946. the driver should expect $value to be in the ODBC standard SQL_DATETIME
  3947. format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc.
  3948. As an alternative to specifying the data type in the C<bind_param> call,
  3949. you can let the driver pass the value as the default type (C<VARCHAR>).
  3950. You can then use an SQL function to convert the type within the statement.
  3951. For example:
  3952. INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
  3953. The C<CONVERT> function used here is just an example. The actual function
  3954. and syntax will vary between different databases and is non-portable.
  3955. See also L</"Placeholders and Bind Values"> for more information.
  3956. =item C<bind_param_inout>
  3957. $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr;
  3958. $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ...
  3959. $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ...
  3960. This method acts like L</bind_param>, but also enables values to be
  3961. updated by the statement. The statement is typically
  3962. a call to a stored procedure. The C<$bind_value> must be passed as a
  3963. reference to the actual value to be used.
  3964. Note that unlike L</bind_param>, the C<$bind_value> variable is not
  3965. copied when C<bind_param_inout> is called. Instead, the value in the
  3966. variable is read at the time L</execute> is called.
  3967. The additional C<$max_len> parameter specifies the minimum amount of
  3968. memory to allocate to C<$bind_value> for the new value. If the value
  3969. returned from the database is too
  3970. big to fit, then the execution should fail. If unsure what value to use,
  3971. pick a generous length, i.e., a length larger than the longest value that would ever be
  3972. returned. The only cost of using a larger value than needed is wasted memory.
  3973. Undefined values or C<undef> are used to indicate null values.
  3974. See also L</"Placeholders and Bind Values"> for more information.
  3975. =item C<bind_param_array>
  3976. $rc = $sth->bind_param_array($p_num, $array_ref_or_value)
  3977. $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr)
  3978. $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type)
  3979. The C<bind_param_array> method is used to bind an array of values
  3980. to a placeholder embedded in the prepared statement which is to be executed
  3981. with L</execute_array>. For example:
  3982. $dbh->{RaiseError} = 1; # save having to check each method call
  3983. $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)");
  3984. $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]);
  3985. $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]);
  3986. $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row
  3987. $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  3988. The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>.
  3989. Refer to L</bind_param> for general details on using placeholders.
  3990. (Note that bind_param_array() can I<not> be used to expand a
  3991. placeholder into a list of values for a statement like "SELECT foo
  3992. WHERE bar IN (?)". A placeholder can only ever represent one value
  3993. per execution.)
  3994. Scalar values, including C<undef>, may also be bound by
  3995. C<bind_param_array>. In which case the same value will be used for each
  3996. L</execute> call. Driver-specific implementations may behave
  3997. differently, e.g., when binding to a stored procedure call, some
  3998. databases may permit mixing scalars and arrays as arguments.
  3999. The default implementation provided by DBI (for drivers that have
  4000. not implemented array binding) is to iteratively call L</execute> for
  4001. each parameter tuple provided in the bound arrays. Drivers may
  4002. provide more optimized implementations using whatever bulk operation
  4003. support the database API provides. The default driver behaviour should
  4004. match the default DBI behaviour, but always consult your driver
  4005. documentation as there may be driver specific issues to consider.
  4006. Note that the default implementation currently only supports non-data
  4007. returning statements (INSERT, UPDATE, but not SELECT). Also,
  4008. C<bind_param_array> and L</bind_param> cannot be mixed in the same
  4009. statement execution, and C<bind_param_array> must be used with
  4010. L</execute_array>; using C<bind_param_array> will have no effect
  4011. for L</execute>.
  4012. The C<bind_param_array> method was added in DBI 1.22.
  4013. =item C<execute>
  4014. $rv = $sth->execute or die $sth->errstr;
  4015. $rv = $sth->execute(@bind_values) or die $sth->errstr;
  4016. Perform whatever processing is necessary to execute the prepared
  4017. statement. An C<undef> is returned if an error occurs. A successful
  4018. C<execute> always returns true regardless of the number of rows affected,
  4019. even if it's zero (see below). It is always important to check the
  4020. return status of C<execute> (and most other DBI methods) for errors
  4021. if you're not using L</RaiseError>.
  4022. For a I<non>-C<SELECT> statement, C<execute> returns the number of rows
  4023. affected, if known. If no rows were affected, then C<execute> returns
  4024. "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it
  4025. is I<not> an error for no rows to be affected by a statement. If the
  4026. number of rows affected is not known, then C<execute> returns -1.
  4027. For C<SELECT> statements, execute simply "starts" the query within the
  4028. database engine. Use one of the fetch methods to retrieve the data after
  4029. calling C<execute>. The C<execute> method does I<not> return the number of
  4030. rows that will be returned by the query (because most databases can't
  4031. tell in advance), it simply returns a true value.
  4032. If any arguments are given, then C<execute> will effectively call
  4033. L</bind_param> for each value before executing the statement. Values
  4034. bound in this way are usually treated as C<SQL_VARCHAR> types unless
  4035. the driver can determine the correct type (which is rare), or unless
  4036. C<bind_param> (or C<bind_param_inout>) has already been used to
  4037. specify the type.
  4038. If execute() is called on a statement handle that's still active
  4039. ($sth->{Active} is true) then it should effectively call finish()
  4040. to tidy up the previous execution results before starting this new
  4041. execution.
  4042. =item C<execute_array>
  4043. $rv = $sth->execute_array(\%attr) or die $sth->errstr;
  4044. $rv = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
  4045. Execute the prepared statement once for each parameter tuple
  4046. (group of values) provided either in the @bind_values, or by prior
  4047. calls to L</bind_param_array>, or via a reference passed in \%attr.
  4048. The execute_array() method returns the number of tuples executed,
  4049. or C<undef> if an error occured. Like execute(), a successful
  4050. execute_array() always returns true regardless of the number of
  4051. tuples executed, even if it's zero. See the C<ArrayTupleStatus>
  4052. attribute below for how to determine the execution status for each
  4053. tuple.
  4054. Bind values for the tuples to be executed may be supplied row-wise
  4055. by an C<ArrayTupleFetch> attribute, or else column-wise in the
  4056. C<@bind_values> argument, or else column-wise by prior calls to
  4057. L</bind_param_array>.
  4058. Where column-wise binding is used (via the C<@bind_values> argument
  4059. or calls to bind_param_array()) the maximum number of elements in
  4060. any one of the bound value arrays determines the number of tuples
  4061. executed. Placeholders with fewer values in their parameter arrays
  4062. are treated as if padded with undef (NULL) values.
  4063. If a scalar value is bound, instead of an array reference, it is
  4064. treated as a I<variable> length array with all elements having the
  4065. same value. It's does not influence the number of tuples executed,
  4066. so if all bound arrays have zero elements then zero tuples will
  4067. be executed. If I<all> bound values are scalars then one tuple
  4068. will be executed, making execute_array() act just like execute().
  4069. The C<ArrayTupleFetch> attribute can be used to specify a reference
  4070. to a subroutine that will be called to provide the bind values for
  4071. each tuple execution. The subroutine should return an reference to
  4072. an array which contains the appropriate number of bind values, or
  4073. return an undef if there is no more data to execute.
  4074. As a convienience, the C<ArrayTupleFetch> attribute can also be
  4075. used to specify a statement handle. In which case the fetchrow_arrayref()
  4076. method will be called on the given statement handle in order to
  4077. provide the bind values for each tuple execution.
  4078. The values specified via bind_param_array() or the @bind_values
  4079. parameter may be either scalars, or arrayrefs. If any C<@bind_values>
  4080. are given, then C<execute_array> will effectively call L</bind_param_array>
  4081. for each value before executing the statement. Values bound in
  4082. this way are usually treated as C<SQL_VARCHAR> types unless the
  4083. driver can determine the correct type (which is rare), or unless
  4084. C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or
  4085. C<bind_param_inout_array> has already been used to specify the type.
  4086. See L</bind_param_array> for details.
  4087. The mandatory C<ArrayTupleStatus> attribute is used to specify a
  4088. reference to an array which will receive the execute status of each
  4089. executed parameter tuple.
  4090. For tuples which are successfully executed, the element at the same
  4091. ordinal position in the status array is the resulting rowcount.
  4092. If the execution of a tuple causes an error, then the corresponding
  4093. status array element will be set to a reference to an array containing
  4094. the error code and error string set by the failed execution.
  4095. If B<any> tuple execution returns an error, C<execute_array> will
  4096. return C<undef>. In that case, the application should inspect the
  4097. status array to determine which parameter tuples failed.
  4098. Some databases may not continue executing tuples beyond the first
  4099. failure. In this case the status array will either hold fewer
  4100. elements, or the elements beyond the failure will be undef.
  4101. If all parameter tuples are successfully executed, C<execute_array>
  4102. returns the number tuples executed. If no tuples were executed,
  4103. then execute_array() returns "C<0E0>", just like execute() does,
  4104. which Perl will treat as 0 but will regard as true.
  4105. For example:
  4106. $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)");
  4107. my $tuples = $sth->execute_array(
  4108. { ArrayTupleStatus => \my @tuple_status },
  4109. \@first_names,
  4110. \@last_names,
  4111. );
  4112. if ($tuples) {
  4113. print "Successfully inserted $tuples records\n";
  4114. }
  4115. else {
  4116. for my $tuple (0..@last_names-1) {
  4117. my $status = $tuple_status[$tuple];
  4118. $status = [0, "Skipped"] unless defined $status;
  4119. next unless ref $status;
  4120. printf "Failed to insert (%s, %s): %s\n",
  4121. $first_names[$tuple], $last_names[$tuple], $status->[1];
  4122. }
  4123. }
  4124. Support for data returning statements such as SELECT is driver-specific
  4125. and subject to change. At present, the default implementation
  4126. provided by DBI only supports non-data returning statements.
  4127. Transaction semantics when using array binding are driver and
  4128. database specific. If C<AutoCommit> is on, the default DBI
  4129. implementation will cause each parameter tuple to be inidividually
  4130. committed (or rolled back in the event of an error). If C<AutoCommit>
  4131. is off, the application is responsible for explicitly committing
  4132. the entire set of bound parameter tuples. Note that different
  4133. drivers and databases may have different behaviours when some
  4134. parameter tuples cause failures. In some cases, the driver or
  4135. database may automatically rollback the effect of all prior parameter
  4136. tuples that succeeded in the transaction; other drivers or databases
  4137. may retain the effect of prior successfully executed parameter
  4138. tuples. Be sure to check your driver and database for its specific
  4139. behaviour.
  4140. Note that, in general, performance will usually be better with
  4141. C<AutoCommit> turned off, and using explicit C<commit> after each
  4142. C<execute_array> call.
  4143. The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch
  4144. was added in 1.36.
  4145. =item C<execute_for_fetch>
  4146. $rc = $sth->execute_for_fetch($fetch_tuple_sub);
  4147. $rc = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
  4148. The execute_for_fetch() method is used to perform bulk operations
  4149. and is most often used via the execute_array() method, not directly.
  4150. The fetch subroutine, referenced by $fetch_tuple_sub, is expected
  4151. to return a reference to an array (known as a 'tuple') or undef.
  4152. The execute_for_fetch() method calls $fetch_tuple_sub, without any
  4153. parameters, until it returns a false value. Each tuple returned is
  4154. used to provide bind values for an $sth->execute(@$tuple) call.
  4155. If there were any errors then C<undef> is returned and the @tuple_status
  4156. array can be used to discover which tuples failed and with what errors.
  4157. If there were no errors then execute_for_fetch() returns the number
  4158. of tuples executed. Like execute() and execute_array() a zero is
  4159. returned as "0E0" so execute_for_fetch() is only false on error.
  4160. If \@tuple_status is passed then the execute_for_fetch method uses
  4161. it to return status information. The tuple_status array holds one
  4162. element per tuple. If the corresponding execute() did not fail then
  4163. the element holds the return value from execute(), which is typically
  4164. a row count. If the execute() did fail then the element holds a
  4165. reference to an array containing ($sth->err, $sth->errstr, $sth->state).
  4166. Although each tuple returned by $fetch_tuple_sub is effectively used
  4167. to call $sth->execute(@$tuple_array_ref) the exact timing may vary.
  4168. Drivers are free to accumulate sets of tuples to pass to the
  4169. database server in bulk group operations for more efficient execution.
  4170. However, the $fetch_tuple_sub is specifically allowed to return
  4171. the same array reference each time (which is what fetchrow_arrayref()
  4172. usually does).
  4173. For example:
  4174. my $sel = $dbh1->prepare("select foo, bar from table1");
  4175. $sel->execute;
  4176. my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)");
  4177. my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref };
  4178. my @tuple_status;
  4179. $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
  4180. my @errors = grep { ref $_ } @tuple_status;
  4181. Similarly, if you already have an array containing the data rows
  4182. to be processed you'd use a subroutine to shift off and return
  4183. each array ref in turn:
  4184. $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status);
  4185. The C<execute_for_fetch> method was added in DBI 1.38.
  4186. =item C<fetchrow_arrayref>
  4187. $ary_ref = $sth->fetchrow_arrayref;
  4188. $ary_ref = $sth->fetch; # alias
  4189. Fetches the next row of data and returns a reference to an array
  4190. holding the field values. Null fields are returned as C<undef>
  4191. values in the array.
  4192. This is the fastest way to fetch data, particularly if used with
  4193. C<$sth-E<gt>bind_columns>.
  4194. If there are no more rows or if an error occurs, then C<fetchrow_arrayref>
  4195. returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
  4196. C<RaiseError> attribute) to discover if the C<undef> returned was due to an
  4197. error.
  4198. Note that the same array reference is returned for each fetch, so don't
  4199. store the reference and then use it after a later fetch. Also, the
  4200. elements of the array are also reused for each row, so take care if you
  4201. want to take a reference to an element. See also L</bind_columns>.
  4202. =item C<fetchrow_array>
  4203. @ary = $sth->fetchrow_array;
  4204. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  4205. and returns it as a list containing the field values. Null fields
  4206. are returned as C<undef> values in the list.
  4207. If there are no more rows or if an error occurs, then C<fetchrow_array>
  4208. returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use
  4209. the C<RaiseError> attribute) to discover if the empty list returned was
  4210. due to an error.
  4211. If called in a scalar context for a statement handle that has more
  4212. than one column, it is undefined whether the driver will return
  4213. the value of the first column or the last. So don't do that.
  4214. Also, in a scalar context, an C<undef> is returned if there are no
  4215. more rows or if an error occurred. That C<undef> can't be distinguished
  4216. from an C<undef> returned because the first field value was NULL.
  4217. For these reasons you should exercise some caution if you use
  4218. C<fetchrow_array> in a scalar context.
  4219. =item C<fetchrow_hashref>
  4220. $hash_ref = $sth->fetchrow_hashref;
  4221. $hash_ref = $sth->fetchrow_hashref($name);
  4222. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  4223. and returns it as a reference to a hash containing field name and field
  4224. value pairs. Null fields are returned as C<undef> values in the hash.
  4225. If there are no more rows or if an error occurs, then C<fetchrow_hashref>
  4226. returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
  4227. C<RaiseError> attribute) to discover if the C<undef> returned was due to an
  4228. error.
  4229. The optional C<$name> parameter specifies the name of the statement handle
  4230. attribute. For historical reasons it defaults to "C<NAME>", however using either
  4231. "C<NAME_lc>" or "C<NAME_uc>" is recomended for portability.
  4232. The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If
  4233. more than one field has the same name, there will only be one entry in
  4234. the returned hash for those fields.
  4235. Because of the extra work C<fetchrow_hashref> and Perl have to perform, it
  4236. is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>.
  4237. By default a reference to a new hash is returned for each row.
  4238. It is likely that a future version of the DBI will support an
  4239. attribute which will enable the same hash to be reused for each
  4240. row. This will give a significant performance boost, but it won't
  4241. be enabled by default because of the risk of breaking old code.
  4242. =item C<fetchall_arrayref>
  4243. $tbl_ary_ref = $sth->fetchall_arrayref;
  4244. $tbl_ary_ref = $sth->fetchall_arrayref( $slice );
  4245. $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
  4246. The C<fetchall_arrayref> method can be used to fetch all the data to be
  4247. returned from a prepared and executed statement handle. It returns a
  4248. reference to an array that contains one reference per row.
  4249. If there are no rows to return, C<fetchall_arrayref> returns a reference
  4250. to an empty array. If an error occurs, C<fetchall_arrayref> returns the
  4251. data fetched thus far, which may be none. You should check C<$sth-E<gt>err>
  4252. afterwards (or use the C<RaiseError> attribute) to discover if the data is
  4253. complete or was truncated due to an error.
  4254. If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref>
  4255. to fetch each row as an array ref. If the $slice array is not empty
  4256. then it is used as a slice to select individual columns by perl array
  4257. index number (starting at 0, unlike column and parameter numbers which
  4258. start at 1).
  4259. With no parameters, or if $slice is undefined, C<fetchall_arrayref>
  4260. acts as if passed an empty array ref.
  4261. If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref>
  4262. to fetch each row as a hash reference. If the $slice hash is empty then
  4263. fetchrow_hashref() is simply called in a tight loop and the keys in the hashes
  4264. have whatever name lettercase is returned by default from fetchrow_hashref.
  4265. (See L</FetchHashKeyName> attribute.) If the $slice hash is not
  4266. empty, then it is used as a slice to select individual columns by
  4267. name. The values of the hash should be set to 1. The key names
  4268. of the returned hashes match the letter case of the names in the
  4269. parameter hash, regardless of the L</FetchHashKeyName> attribute.
  4270. For example, to fetch just the first column of every row:
  4271. $tbl_ary_ref = $sth->fetchall_arrayref([0]);
  4272. To fetch the second to last and last column of every row:
  4273. $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
  4274. To fetch all fields of every row as a hash ref:
  4275. $tbl_ary_ref = $sth->fetchall_arrayref({});
  4276. To fetch only the fields called "foo" and "bar" of every row as a hash ref
  4277. (with keys named "foo" and "BAR"):
  4278. $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 });
  4279. The first two examples return a reference to an array of array refs.
  4280. The third and forth return a reference to an array of hash refs.
  4281. If $max_rows is defined and greater than or equal to zero then it
  4282. is used to limit the number of rows fetched before returning.
  4283. fetchall_arrayref() can then be called again to fetch more rows.
  4284. This is especially useful when you need the better performance of
  4285. fetchall_arrayref() but don't have enough memory to fetch and return
  4286. all the rows in one go. Here's an example:
  4287. my $rows = []; # cache for batches of rows
  4288. while( my $row = ( shift(@$rows) || # get row from cache, or reload cache:
  4289. shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) )
  4290. ) {
  4291. ...
  4292. }
  4293. That can be the fastest way to fetch and process lots of rows using the DBI,
  4294. but it depends on the relative cost of method calls vs memory allocation.
  4295. A standard C<while> loop with column binding is often faster because
  4296. the cost of allocating memory for the batch of rows is greater than
  4297. the saving by reducing method calls. It's possible that the DBI may
  4298. provide a way to reuse the memory of a previous batch in future, which
  4299. would then shift the balance back towards fetchall_arrayref().
  4300. =item C<fetchall_hashref>
  4301. $hash_ref = $sth->fetchall_hashref($key_field);
  4302. The C<fetchall_hashref> method can be used to fetch all the data to be
  4303. returned from a prepared and executed statement handle. It returns a
  4304. reference to a hash that contains, at most, one entry per row.
  4305. If there are no rows to return, C<fetchall_hashref> returns a reference
  4306. to an empty hash. If an error occurs, C<fetchall_hashref> returns the
  4307. data fetched thus far, which may be none. You should check
  4308. C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to
  4309. discover if the data is complete or was truncated due to an error.
  4310. The $key_field parameter provides the name of the field that holds the
  4311. value to be used for the key for the returned hash. For example:
  4312. $dbh->{FetchHashKeyName} = 'NAME_lc';
  4313. $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE");
  4314. $sth->execute;
  4315. $hash_ref = $sth->fetchall_hashref('id');
  4316. print "Name for id 42 is $hash_ref->{42}->{name}\n";
  4317. The $key_field parameter can also be specified as an integer column
  4318. number (counting from 1). If $key_field doesn't match any column in
  4319. the statement, as a name first then as a number, then an error is
  4320. returned.
  4321. This method is normally used only where the key field value for each
  4322. row is unique. If multiple rows are returned with the same value for
  4323. the key field then later rows overwrite earlier ones.
  4324. =item C<finish>
  4325. $rc = $sth->finish;
  4326. Indicate that no more data will be fetched from this statement handle
  4327. before it is either executed again or destroyed. The C<finish> method
  4328. is rarely needed, and frequently overused, but can sometimes be
  4329. helpful in a few very specific situations to allow the server to free
  4330. up resources (such as sort buffers).
  4331. When all the data has been fetched from a C<SELECT> statement, the
  4332. driver should automatically call C<finish> for you. So you should
  4333. I<not> normally need to call it explicitly I<except> when you know
  4334. that you've not fetched all the data from a statement handle.
  4335. The most common example is when you only want to fetch one row,
  4336. but in that case the C<selectrow_*> methods are usually better anyway.
  4337. Adding calls to C<finish> after each fetch loop is a common mistake,
  4338. don't do it, it can mask genuine problems like uncaught fetch errors.
  4339. Consider a query like:
  4340. SELECT foo FROM table WHERE bar=? ORDER BY foo
  4341. where you want to select just the first (smallest) "foo" value from a
  4342. very large table. When executed, the database server will have to use
  4343. temporary buffer space to store the sorted rows. If, after executing
  4344. the handle and selecting one row, the handle won't be re-executed for
  4345. some time and won't be destroyed, the C<finish> method can be used to tell
  4346. the server that the buffer space can be freed.
  4347. Calling C<finish> resets the L</Active> attribute for the statement. It
  4348. may also make some statement handle attributes (such as C<NAME> and C<TYPE>)
  4349. unavailable if they have not already been accessed (and thus cached).
  4350. The C<finish> method does not affect the transaction status of the
  4351. database connection. It has nothing to do with transactions. It's mostly an
  4352. internal "housekeeping" method that is rarely needed.
  4353. See also L</disconnect> and the L</Active> attribute.
  4354. The C<finish> method should have been called C<discard_pending_rows>.
  4355. =item C<rows>
  4356. $rv = $sth->rows;
  4357. Returns the number of rows affected by the last row affecting command,
  4358. or -1 if the number of rows is not known or not available.
  4359. Generally, you can only rely on a row count after a I<non>-C<SELECT>
  4360. C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or
  4361. after fetching all the rows of a C<SELECT> statement.
  4362. For C<SELECT> statements, it is generally not possible to know how many
  4363. rows will be returned except by fetching them all. Some drivers will
  4364. return the number of rows the application has fetched so far, but
  4365. others may return -1 until all rows have been fetched. So use of the
  4366. C<rows> method or C<$DBI::rows> with C<SELECT> statements is not
  4367. recommended.
  4368. One alternative method to get a row count for a C<SELECT> is to execute a
  4369. "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your
  4370. query and then fetch the row count from that.
  4371. =item C<bind_col>
  4372. $rc = $sth->bind_col($column_number, \$var_to_bind);
  4373. $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr );
  4374. $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type );
  4375. Binds a Perl variable and/or some attributes to an output column
  4376. (field) of a C<SELECT> statement. Column numbers count up from 1.
  4377. You do not need to bind output columns in order to fetch data.
  4378. For maximum portability between drivers, bind_col() should be called
  4379. after execute() and not before.
  4380. See also C<bind_columns> for an example.
  4381. The binding is performed at a low level using Perl aliasing.
  4382. Whenever a row is fetched from the database $var_to_bind appears
  4383. to be automatically updated simply because it refers to the same
  4384. memory location as the corresponding column value. This makes using
  4385. bound variables very efficient. Multiple variables can be bound
  4386. to a single column, but there's rarely any point. Binding a tied
  4387. variable doesn't work, currently.
  4388. The L</bind_param> method
  4389. performs a similar, but opposite, function for input variables.
  4390. B<Data Types for Column Binding>
  4391. The C<\%attr> parameter can be used to hint at the data type
  4392. formatting the column should have. For example, you can use:
  4393. $sth->bind_col(1, undef, { TYPE => SQL_DATETIME });
  4394. to specify that you'd like the column (which presumably is some
  4395. kind of datetime type) to be returned in the standard format for
  4396. SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the
  4397. native formatting the database would normally use.
  4398. There's no $var_to_bind in that example to emphasize the point
  4399. that bind_col() works on the underlying column value and not just
  4400. a particular bound variable.
  4401. As a short-cut for the common case, the data type can be passed
  4402. directly, in place of the C<\%attr> hash reference. This example is
  4403. equivalent to the one above:
  4404. $sth->bind_col(1, undef, SQL_DATETIME);
  4405. The C<TYPE> value indicates the standard (non-driver-specific) type for
  4406. this parameter. To specify the driver-specific type, the driver may
  4407. support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>.
  4408. The SQL_DATETIME and other related constants can be imported using
  4409. use DBI qw(:sql_types);
  4410. See L</"DBI Constants"> for more information.
  4411. The data type for a bind variable cannot be changed after the first
  4412. C<bind_col> call. In fact the whole \%attr parameter is 'sticky'
  4413. in the sense that a driver only needs to consider the \%attr parameter
  4414. for the first call for a given $sth and column.
  4415. The TYPE attribute for bind_col() was first specified in DBI 1.41.
  4416. =item C<bind_columns>
  4417. $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
  4418. Calls L</bind_col> for each column of the C<SELECT> statement.
  4419. The C<bind_columns> method will die if the number of references does not
  4420. match the number of fields.
  4421. For maximum portability between drivers, bind_columns() should be called
  4422. after execute() and not before.
  4423. For example:
  4424. $dbh->{RaiseError} = 1; # do this, or check every call for errors
  4425. $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
  4426. $sth->execute;
  4427. my ($region, $sales);
  4428. # Bind Perl variables to columns:
  4429. $rv = $sth->bind_columns(\$region, \$sales);
  4430. # you can also use Perl's \(...) syntax (see perlref docs):
  4431. # $sth->bind_columns(\($region, $sales));
  4432. # Column binding is the most efficient way to fetch data
  4433. while ($sth->fetch) {
  4434. print "$region: $sales\n";
  4435. }
  4436. For compatibility with old scripts, the first parameter will be
  4437. ignored if it is C<undef> or a hash reference.
  4438. Here's a more fancy example that binds columns to the values I<inside>
  4439. a hash (thanks to H.Merijn Brand):
  4440. $sth->execute;
  4441. my %row;
  4442. $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } ));
  4443. while ($sth->fetch) {
  4444. print "$row{region}: $row{sales}\n";
  4445. }
  4446. =item C<dump_results>
  4447. $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
  4448. Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and
  4449. prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep>
  4450. (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35.
  4451. This method is designed as a handy utility for prototyping and
  4452. testing queries. Since it uses L</neat_list> to
  4453. format and edit the string for reading by humans, it is not recomended
  4454. for data transfer applications.
  4455. =back
  4456. =head2 Statement Handle Attributes
  4457. This section describes attributes specific to statement handles. Most
  4458. of these attributes are read-only.
  4459. Changes to these statement handle attributes do not affect any other
  4460. existing or future statement handles.
  4461. Attempting to set or get the value of an unknown attribute generates a warning,
  4462. except for private driver specific attributes (which all have names
  4463. starting with a lowercase letter).
  4464. Example:
  4465. ... = $h->{NUM_OF_FIELDS}; # get/read
  4466. Some drivers cannot provide valid values for some or all of these
  4467. attributes until after C<$sth-E<gt>execute> has been successfully
  4468. called. Typically the attribute will be C<undef> in these situations.
  4469. Some attributes, like NAME, are not appropriate to some types of
  4470. statement, like SELECT. Typically the attribute will be C<undef>
  4471. in these situations.
  4472. See also L</finish> to learn more about the effect it
  4473. may have on some attributes.
  4474. =over 4
  4475. =item C<NUM_OF_FIELDS> (integer, read-only)
  4476. Number of fields (columns) in the data the prepared statement may return.
  4477. Statements that don't return rows of data, like C<DELETE> and C<CREATE>
  4478. set C<NUM_OF_FIELDS> to 0.
  4479. =item C<NUM_OF_PARAMS> (integer, read-only)
  4480. The number of parameters (placeholders) in the prepared statement.
  4481. See SUBSTITUTION VARIABLES below for more details.
  4482. =item C<NAME> (array-ref, read-only)
  4483. Returns a reference to an array of field names for each column. The
  4484. names may contain spaces but should not be truncated or have any
  4485. trailing space. Note that the names have the letter case (upper, lower
  4486. or mixed) as returned by the driver being used. Portable applications
  4487. should use L</NAME_lc> or L</NAME_uc>.
  4488. print "First column name: $sth->{NAME}->[0]\n";
  4489. =item C<NAME_lc> (array-ref, read-only)
  4490. Like L</NAME> but always returns lowercase names.
  4491. =item C<NAME_uc> (array-ref, read-only)
  4492. Like L</NAME> but always returns uppercase names.
  4493. =item C<NAME_hash> (hash-ref, read-only)
  4494. =item C<NAME_lc_hash> (hash-ref, read-only)
  4495. =item C<NAME_uc_hash> (hash-ref, read-only)
  4496. The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes
  4497. return column name information as a reference to a hash.
  4498. The keys of the hash are the names of the columns. The letter case of
  4499. the keys corresponds to the letter case returned by the C<NAME>,
  4500. C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above).
  4501. The value of each hash entry is the perl index number of the
  4502. corresponding column (counting from 0). For example:
  4503. $sth = $dbh->prepare("select Id, Name from table");
  4504. $sth->execute;
  4505. @row = $sth->fetchrow_array;
  4506. print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n";
  4507. =item C<TYPE> (array-ref, read-only)
  4508. Returns a reference to an array of integer values for each
  4509. column. The value indicates the data type of the corresponding column.
  4510. The values correspond to the international standards (ANSI X3.135
  4511. and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific
  4512. types that don't exactly match standard types should generally return
  4513. the same values as an ODBC driver supplied by the makers of the
  4514. database. That might include private type numbers in ranges the vendor
  4515. has officially registered with the ISO working group:
  4516. ftp://sqlstandards.org/SC32/SQL_Registry/
  4517. Where there's no vendor-supplied ODBC driver to be compatible with,
  4518. the DBI driver can use type numbers in the range that is now
  4519. officially reserved for use by the DBI: -9999 to -9000.
  4520. All possible values for C<TYPE> should have at least one entry in the
  4521. output of the C<type_info_all> method (see L</type_info_all>).
  4522. =item C<PRECISION> (array-ref, read-only)
  4523. Returns a reference to an array of integer values for each column.
  4524. For numeric columns, the value is the maximum number of digits
  4525. (without considering a sign character or decimal point). Note that
  4526. the "display size" for floating point types (REAL, FLOAT, DOUBLE)
  4527. can be up to 7 characters greater than the precision (for the
  4528. sign + decimal point + the letter E + a sign + 2 or 3 digits).
  4529. For any character type column the value is the OCTET_LENGTH,
  4530. in other words the number of bytes, not characters.
  4531. (More recent standards refer to this as COLUMN_SIZE but we stick
  4532. with PRECISION for backwards compatibility.)
  4533. =item C<SCALE> (array-ref, read-only)
  4534. Returns a reference to an array of integer values for each column.
  4535. NULL (C<undef>) values indicate columns where scale is not applicable.
  4536. =item C<NULLABLE> (array-ref, read-only)
  4537. Returns a reference to an array indicating the possibility of each
  4538. column returning a null. Possible values are C<0>
  4539. (or an empty string) = no, C<1> = yes, C<2> = unknown.
  4540. print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
  4541. =item C<CursorName> (string, read-only)
  4542. Returns the name of the cursor associated with the statement handle, if
  4543. available. If not available or if the database driver does not support the
  4544. C<"where current of ..."> SQL syntax, then it returns C<undef>.
  4545. =item C<Database> (dbh, read-only)
  4546. Returns the parent $dbh of the statement handle.
  4547. =item C<ParamValues> (hash ref, read-only)
  4548. Returns a reference to a hash containing the values currently bound
  4549. to placeholders. The keys of the hash are the 'names' of the
  4550. placeholders, typically integers starting at 1. Returns undef if
  4551. not supported by the driver.
  4552. See L</ShowErrorStatement> for an example of how this is used.
  4553. If the driver supports C<ParamValues> but no values have been bound
  4554. yet then the driver should return a hash with placeholders names
  4555. in the keys but all the values undef, but some drivers may return
  4556. a ref to an empty hash.
  4557. It is possible that the values in the hash returned by C<ParamValues>
  4558. are not I<exactly> the same as those passed to bind_param() or execute().
  4559. The driver may have slightly modified values in some way based on the
  4560. TYPE the value was bound with. For example a floating point value
  4561. bound as an SQL_INTEGER type may be returned as an integer.
  4562. The values returned by C<ParamValues> can be passed to another
  4563. bind_param() method with the same TYPE and will be seen by the
  4564. database as the same value.
  4565. It is also possible that the keys in the hash returned by C<ParamValues>
  4566. are not exactly the same as those implied by the prepared statement.
  4567. For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>'
  4568. where N is a sequence number starting at 1.
  4569. The C<ParamValues> attribute was added in DBI 1.28.
  4570. =item C<Statement> (string, read-only)
  4571. Returns the statement string passed to the L</prepare> method.
  4572. =item C<RowsInCache> (integer, read-only)
  4573. If the driver supports a local row cache for C<SELECT> statements, then
  4574. this attribute holds the number of un-fetched rows in the cache. If the
  4575. driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch
  4576. rows on execute, whereas others wait till the first fetch.
  4577. See also the L</RowCacheSize> database handle attribute.
  4578. =back
  4579. =head1 OTHER METHODS
  4580. =over 4
  4581. =item C<install_method>
  4582. DBD::Foo::db->install_method($method_name, \%attr);
  4583. Installs the driver-private method named by $method_name into the
  4584. DBI method dispatcher so it can be called directly, avoiding the
  4585. need to use the func() method.
  4586. It is called as a static method on the driver class to which the
  4587. method belongs. The method name must begin with the corresponding
  4588. registered driver-private prefix. For example, for DBD::Oracle
  4589. $method_name must being with 'C<ora_>', and for DBD::AnyData it
  4590. must begin with 'C<ad_>'.
  4591. The attributes can be used to provide fine control over how the DBI
  4592. dispatcher handles the dispatching of the method. However, at this
  4593. point, it's undocumented and very liable to change. (Volunteers to
  4594. polish up and document the interface are very welcome to get in
  4595. touch via dbi-dev@perl.org)
  4596. Methods installed using install_method default to the standard error
  4597. handling behaviour for DBI methods: clearing err and errstr before
  4598. calling the method, and checking for errors to trigger RaiseError
  4599. etc. on return. This differs from the default behaviour of func().
  4600. Note for driver authors: The DBD::Foo::xx->install_method call won't
  4601. work until the class-hierarchy has been setup. Normally the DBI
  4602. looks after that just after the driver is loaded. This means
  4603. install_method() can't be called at the time the driver is loaded
  4604. unless the class-hierarchy is set up first. The way to do that is
  4605. to call the setup_driver() method:
  4606. DBI->setup_driver('DBD::Foo');
  4607. before using install_method().
  4608. =back
  4609. =head1 FURTHER INFORMATION
  4610. =head2 Catalog Methods
  4611. An application can retrieve metadata information from the DBMS by issuing
  4612. appropriate queries on the views of the Information Schema. Unfortunately,
  4613. C<INFORMATION_SCHEMA> views are seldom supported by the DBMS.
  4614. Special methods (catalog methods) are available to return result sets
  4615. for a small but important portion of that metadata:
  4616. column_info
  4617. foreign_key_info
  4618. primary_key_info
  4619. table_info
  4620. All catalog methods accept arguments in order to restrict the result sets.
  4621. Passing C<undef> to an optional argument does not constrain the search for
  4622. that argument.
  4623. However, an empty string ('') is treated as a regular search criteria
  4624. and will only match an empty value.
  4625. B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An
  4626. empty string will not restrict the result set in SQL/CLI.
  4627. Most arguments in the catalog methods accept only I<ordinary values>, e.g.
  4628. the arguments of C<primary_key_info()>.
  4629. Such arguments are treated as a literal string, i.e. the case is significant
  4630. and quote characters are taken literally.
  4631. Some arguments in the catalog methods accept I<search patterns> (strings
  4632. containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>.
  4633. Passing '%' is equivalent to leaving the argument C<undef>.
  4634. B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers.
  4635. Passing such a value to a search pattern argument may return more rows than
  4636. expected!
  4637. To include pattern characters as literals, they must be preceded by an
  4638. escape character which can be achieved with
  4639. $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE
  4640. $search_pattern =~ s/([_%])/$esc$1/g;
  4641. The ODBC and SQL/CLI specifications define a way to change the default
  4642. behaviour described above: All arguments (except I<list value arguments>)
  4643. are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is
  4644. set to C<SQL_TRUE>.
  4645. I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their
  4646. body (the string within the quotes) is interpreted literally.
  4647. I<Unquoted identifiers> are compared in UPPERCASE.
  4648. The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute,
  4649. i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to
  4650. C<SQL_FALSE>.
  4651. =head2 Transactions
  4652. Transactions are a fundamental part of any robust database system. They
  4653. protect against errors and database corruption by ensuring that sets of
  4654. related changes to the database take place in atomic (indivisible,
  4655. all-or-nothing) units.
  4656. This section applies to databases that support transactions and where
  4657. C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit>
  4658. with various types of databases.
  4659. The recommended way to implement robust transactions in Perl
  4660. applications is to use C<RaiseError> and S<C<eval { ... }>>
  4661. (which is very fast, unlike S<C<eval "...">>). For example:
  4662. $dbh->{AutoCommit} = 0; # enable transactions, if possible
  4663. $dbh->{RaiseError} = 1;
  4664. eval {
  4665. foo(...) # do lots of work here
  4666. bar(...) # including inserts
  4667. baz(...) # and updates
  4668. $dbh->commit; # commit the changes if we get this far
  4669. };
  4670. if ($@) {
  4671. warn "Transaction aborted because $@";
  4672. # now rollback to undo the incomplete changes
  4673. # but do it in an eval{} as it may also fail
  4674. eval { $dbh->rollback };
  4675. # add other application on-error-clean-up code here
  4676. }
  4677. If the C<RaiseError> attribute is not set, then DBI calls would need to be
  4678. manually checked for errors, typically like this:
  4679. $h->method(@args) or die $h->errstr;
  4680. With C<RaiseError> set, the DBI will automatically C<die> if any DBI method
  4681. call on that handle (or a child handle) fails, so you don't have to
  4682. test the return value of each method call. See L</RaiseError> for more
  4683. details.
  4684. A major advantage of the C<eval> approach is that the transaction will be
  4685. properly rolled back if I<any> code (not just DBI calls) in the inner
  4686. application dies for any reason. The major advantage of using the
  4687. C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked
  4688. automatically. Both techniques are strongly recommended.
  4689. After calling C<commit> or C<rollback> many drivers will not let you
  4690. fetch from a previously active C<SELECT> statement handle that's a child
  4691. of the same database handle. A typical way round this is to connect the
  4692. the database twice and use one connection for C<SELECT> statements.
  4693. See L</AutoCommit> and L</disconnect> for other important information
  4694. about transactions.
  4695. =head2 Handling BLOB / LONG / Memo Fields
  4696. Many databases support "blob" (binary large objects), "long", or similar
  4697. datatypes for holding very long strings or large amounts of binary
  4698. data in a single field. Some databases support variable length long
  4699. values over 2,000,000,000 bytes in length.
  4700. Since values of that size can't usually be held in memory, and because
  4701. databases can't usually know in advance the length of the longest long
  4702. that will be returned from a C<SELECT> statement (unlike other data
  4703. types), some special handling is required.
  4704. In this situation, the value of the C<$h-E<gt>{LongReadLen}>
  4705. attribute is used to determine how much buffer space to allocate
  4706. when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute
  4707. is used to determine how to behave if a fetched value can't fit
  4708. into the buffer.
  4709. See the description of L</LongReadLen> for more information.
  4710. When trying to insert long or binary values, placeholders should be used
  4711. since there are often limits on the maximum size of an C<INSERT>
  4712. statement and the L</quote> method generally can't cope with binary
  4713. data. See L</Placeholders and Bind Values>.
  4714. =head2 Simple Examples
  4715. Here's a complete example program to select and fetch some data:
  4716. my $data_source = "dbi::DriverName:db_name";
  4717. my $dbh = DBI->connect($data_source, $user, $password)
  4718. or die "Can't connect to $data_source: $DBI::errstr";
  4719. my $sth = $dbh->prepare( q{
  4720. SELECT name, phone
  4721. FROM mytelbook
  4722. }) or die "Can't prepare statement: $DBI::errstr";
  4723. my $rc = $sth->execute
  4724. or die "Can't execute statement: $DBI::errstr";
  4725. print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
  4726. print "Field names: @{ $sth->{NAME} }\n";
  4727. while (($name, $phone) = $sth->fetchrow_array) {
  4728. print "$name: $phone\n";
  4729. }
  4730. # check for problems which may have terminated the fetch early
  4731. die $sth->errstr if $sth->err;
  4732. $dbh->disconnect;
  4733. Here's a complete example program to insert some data from a file.
  4734. (This example uses C<RaiseError> to avoid needing to check each call).
  4735. my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
  4736. RaiseError => 1, AutoCommit => 0
  4737. });
  4738. my $sth = $dbh->prepare( q{
  4739. INSERT INTO table (name, phone) VALUES (?, ?)
  4740. });
  4741. open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
  4742. while (<FH>) {
  4743. chomp;
  4744. my ($name, $phone) = split /,/;
  4745. $sth->execute($name, $phone);
  4746. }
  4747. close FH;
  4748. $dbh->commit;
  4749. $dbh->disconnect;
  4750. Here's how to convert fetched NULLs (undefined values) into empty strings:
  4751. while($row = $sth->fetchrow_arrayref) {
  4752. # this is a fast and simple way to deal with nulls:
  4753. foreach (@$row) { $_ = '' unless defined }
  4754. print "@$row\n";
  4755. }
  4756. The C<q{...}> style quoting used in these examples avoids clashing with
  4757. quotes that may be used in the SQL statement. Use the double-quote like
  4758. C<qq{...}> operator if you want to interpolate variables into the string.
  4759. See L<perlop/"Quote and Quote-like Operators"> for more details.
  4760. =head2 Threads and Thread Safety
  4761. Perl 5.7 and later support a new threading model called iThreads.
  4762. (The old "5.005 style" threads are not supported by the DBI.)
  4763. In the iThreads model each thread has it's own copy of the perl
  4764. interpreter. When a new thread is created the original perl
  4765. interpreter is 'cloned' to create a new copy for the new thread.
  4766. If the DBI and drivers are loaded and handles created before the
  4767. thread is created then it will get a cloned copy of the DBI, the
  4768. drivers and the handles.
  4769. However, the internal pointer data within the handles will refer
  4770. to the DBI and drivers in the original interpreter. Using those
  4771. handles in the new interpreter thread is not safe, so the DBI detects
  4772. this and croaks on any method call using handles that don't belong
  4773. to the current thread (except for DESTROY).
  4774. Because of this (possibly temporary) restriction, newly created
  4775. threads must make their own connctions to the database. Handles
  4776. can't be shared across threads.
  4777. But BEWARE, some underlying database APIs (the code the DBD driver
  4778. uses to talk to the database, often supplied by the database vendor)
  4779. are not thread safe. If it's not thread safe, then allowing more
  4780. than one thread to enter the code at the same time may cause
  4781. subtle/serious problems. In some cases allowing more than
  4782. one thread to enter the code, even if I<not> at the same time,
  4783. can cause problems. You have been warned.
  4784. Using DBI with perl threads is not yet recommended for production
  4785. environments. For more information see
  4786. L<http://www.perlmonks.org/index.pl?node_id=288022>
  4787. Note: There is a bug in perl 5.8.2 when configured with threads
  4788. and debugging enabled (bug #24463) which causes a DBI test to fail.
  4789. =head2 Signal Handling and Canceling Operations
  4790. [The following only applies to systems with unix-like signal handling.
  4791. I'd welcome additions for other systems, especially Windows.]
  4792. The first thing to say is that signal handling in Perl versions less
  4793. than 5.8 is I<not> safe. There is always a small risk of Perl
  4794. crashing and/or core dumping when, or after, handling a signal
  4795. because the signal could arrive and be handled while internal data
  4796. structures are being changed. If the signal handling code
  4797. used those same internal data structures it could cause all manner
  4798. of subtle and not-so-subtle problems. The risk was reduced with
  4799. 5.4.4 but was still present in all perls up through 5.8.0.
  4800. Beginning in perl 5.8.0 perl implements 'safe' signal handling if
  4801. your system has the POSIX sigaction() routine. Now when a signal
  4802. is delivered perl just makes a note of it but does I<not> run the
  4803. %SIG handler. The handling is 'defered' until a 'safe' moment.
  4804. Although this change made signal handling safe, it also lead to
  4805. a problem with signals being defered for longer than you'd like.
  4806. If a signal arrived while executing a system call, such as waiting
  4807. for data on a network connection, the signal is noted and then the
  4808. system call that was executing returns with an EINTR error code
  4809. to indicate that it was interrupted. All fine so far.
  4810. The problem comes when the code that made the system call sees the
  4811. EINTR code and decides it's going to call it again. Perl doesn't
  4812. do that, but database code sometimes does. If that happens then the
  4813. signal handler doesn't get called untill later. Maybe much later.
  4814. Fortunately there are ways around this which we'll discuss below.
  4815. Unfortunately they make signals unsafe again.
  4816. The two most common uses of signals in relation to the DBI are for
  4817. canceling operations when the user types Ctrl-C (interrupt), and for
  4818. implementing a timeout using C<alarm()> and C<$SIG{ALRM}>.
  4819. =over 4
  4820. =item Cancel
  4821. The DBI provides a C<cancel> method for statement handles. The
  4822. C<cancel> method should abort the current operation and is designed
  4823. to be called from a signal handler. For example:
  4824. $SIG{INT} = sub { $sth->cancel };
  4825. However, few drivers implement this (the DBI provides a default
  4826. method that just returns C<undef>) and, even if implemented, there
  4827. is still a possibility that the statement handle, and even the
  4828. parent database handle, will not be usable afterwards.
  4829. If C<cancel> returns true, then it has successfully
  4830. invoked the database engine's own cancel function. If it returns false,
  4831. then C<cancel> failed. If it returns C<undef>, then the database
  4832. driver does not have cancel implemented.
  4833. =item Timeout
  4834. The traditional way to implement a timeout is to set C<$SIG{ALRM}>
  4835. to refer to some code that will be executed when an ALRM signal
  4836. arrives and then to call alarm($seconds) to schedule an ALRM signal
  4837. to be delivered $seconds in the future. For example:
  4838. eval {
  4839. local $SIG{ALRM} = sub { die "TIMEOUT\n" };
  4840. alarm($seconds);
  4841. ... code to execute with timeout here ...
  4842. alarm(0); # cancel alarm (if code ran fast)
  4843. };
  4844. alarm(0); # cancel alarm (if eval failed)
  4845. if ( $@ eq "TIMEOUT" ) { ... }
  4846. Unfortunately, as described above, this won't always work as expected,
  4847. depending on your perl version and the underlying database code.
  4848. With Oracle for instance (DBD::Oracle), if the system which hosts
  4849. the database is down the DBI->connect() call will hang for several
  4850. minutes before returning an error.
  4851. =back
  4852. The solution on these systems is to use the C<POSIX::sigaction()>
  4853. routine to gain low level access to how the signal handler is installed.
  4854. The code would look something like this (for the DBD-Oracle connect()):
  4855. use POSIX ':signal_h';
  4856. my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler
  4857. my $action = POSIX::SigAction->new(
  4858. sub { die "connect timeout" }, # the handler code ref
  4859. $mask,
  4860. # not using (perl 5.8.2 and later) 'safe' switch or sa_flags
  4861. );
  4862. my $oldaction = POSIX::SigAction->new();
  4863. sigaction( 'ALRM', $action, $oldaction );
  4864. my $dbh;
  4865. eval {
  4866. alarm(5); # seconds before time out
  4867. $dbh = DBI->connect("dbi:Oracle:$dsn" ... );
  4868. alarm(0); # cancel alarm (if connect worked fast)
  4869. };
  4870. alarm(0); # cancel alarm (if eval failed)
  4871. sigaction( 'ALRM', $oldaction ); # restore original signal handler
  4872. if ( $@ ) ....
  4873. Similar techniques can be used for canceling statement execution.
  4874. Unfortunately, this solution is somewhat messy, and it does I<not> work with
  4875. perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken.
  4876. For a cleaner implementation that works across perl versions, see Lincoln Baxter's
  4877. Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>.
  4878. The documentation for Sys::SigAction includes an longer discussion
  4879. of this problem, and a DBD::Oracle test script.
  4880. Be sure to read all the signal handling sections of the L<perlipc> manual.
  4881. And finally, two more points to keep firmly in mind. Firstly,
  4882. remember that what we've done here is essentially revert to old
  4883. style I<unsafe> handling of these signals. So do as little as
  4884. possible in the handler. Ideally just die(). Secondly, the handles
  4885. in use at the time the signal is handled may not be safe to use
  4886. afterwards.
  4887. =head2 Subclassing the DBI
  4888. DBI can be subclassed and extended just like any other object
  4889. oriented module. Before we talk about how to do that, it's important
  4890. to be clear about how the DBI classes and how they work together.
  4891. By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed
  4892. into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method
  4893. returns an $sth blessed into the C<DBI::st> class (actually it
  4894. simply changes the last four characters of the calling handle class
  4895. to be C<::st>).
  4896. The leading 'C<DBI>' is known as the 'root class' and the extra
  4897. 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want
  4898. to subclass the DBI you'll need to put your overriding methods into
  4899. the appropriate classes. For example, if you want to use a root class
  4900. of C<MySubDBI> and override the do(), prepare() and execute() methods,
  4901. then your do() and prepare() methods should be in the C<MySubDBI::db>
  4902. class and the execute() method should be in the C<MySubDBI::st> class.
  4903. To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db>
  4904. should include C<DBI::db> and the @ISA variable in C<MySubDBI::st>
  4905. should include C<DBI::st>. The C<MySubDBI> root class itself isn't
  4906. currently used for anything visible and so, apart from setting @ISA
  4907. to include C<DBI>, it should be left empty.
  4908. So, having put your overriding methods into the right classes, and
  4909. setup the inheritance hierarchy, how do you get the DBI to use them?
  4910. You have two choices, either a static method call using the name
  4911. of your subclass:
  4912. $dbh = MySubDBI->connect(...);
  4913. or specifying a C<RootClass> attribute:
  4914. $dbh = DBI->connect(..., { RootClass => 'MySubDBI' });
  4915. The only difference between the two is that using an explicit
  4916. RootClass attribute will make the DBI automatically attempt to load
  4917. a module by that name if the class doesn't exist.
  4918. If both forms are used then the attribute takes precedence.
  4919. When subclassing is being used then, after a successful new
  4920. connect, the DBI->connect method automatically calls:
  4921. $dbh->connected($dsn, $user, $pass, \%attr);
  4922. The default method does nothing. The call is made just to simplify
  4923. any post-connection setup that your subclass may want to perform.
  4924. If your subclass supplies a connected method, it should be part of the
  4925. MySubDBI::db package.
  4926. Here's a brief example of a DBI subclass. A more thorough example
  4927. can be found in t/subclass.t in the DBI distribution.
  4928. package MySubDBI;
  4929. use strict;
  4930. use DBI;
  4931. use vars qw(@ISA);
  4932. @ISA = qw(DBI);
  4933. package MySubDBI::db;
  4934. use vars qw(@ISA);
  4935. @ISA = qw(DBI::db);
  4936. sub prepare {
  4937. my ($dbh, @args) = @_;
  4938. my $sth = $dbh->SUPER::prepare(@args)
  4939. or return;
  4940. $sth->{private_mysubdbi_info} = { foo => 'bar' };
  4941. return $sth;
  4942. }
  4943. package MySubDBI::st;
  4944. use vars qw(@ISA);
  4945. @ISA = qw(DBI::st);
  4946. sub fetch {
  4947. my ($sth, @args) = @_;
  4948. my $row = $sth->SUPER::fetch(@args)
  4949. or return;
  4950. do_something_magical_with_row_data($row)
  4951. or return $sth->set_err(1234, "The magic failed", undef, "fetch");
  4952. return $row;
  4953. }
  4954. When calling a SUPER::method that returns a handle, be careful to
  4955. check the return value before trying to do other things with it in
  4956. your overridden method. This is especially important if you want
  4957. to set a hash attribute on the handle, as Perl's autovivification
  4958. will bite you by (in)conveniently creating an unblessed hashref,
  4959. which your method will then return with usually baffling results
  4960. later on. It's best to check right after the call and return undef
  4961. immediately on error, just like DBI would and just like the example
  4962. above.
  4963. If your method needs to record an error it should call the set_err()
  4964. method with the error code and error string, as shown in the example
  4965. above. The error code and error string will be recorded in the
  4966. handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc.
  4967. The set_err() method always returns an undef or empty list as
  4968. approriate. Since your method should nearly always return an undef
  4969. or empty list as soon as an error is detected it's handy to simply
  4970. return what set_err() returns, as shown in the example above.
  4971. If the handle has C<RaiseError>, C<PrintError>, or C<HandleError>
  4972. etc. set then the set_err() method will honour them. This means
  4973. that if C<RaiseError> is set then set_err() won't return in the
  4974. normal way but will 'throw an exception' that can be caught with
  4975. an C<eval> block.
  4976. You can stash private data into DBI handles
  4977. via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES
  4978. COMMON TO ALL HANDLES> for info and important caveats.
  4979. =head1 TRACING
  4980. The DBI has a powerful tracing mechanism built in. It enables you
  4981. to see what's going on 'behind the scenes', both within the DBI and
  4982. the drivers you're using.
  4983. =head2 Trace Settings
  4984. Which details are written to the trace output is controlled by a
  4985. combination of a I<trace level>, an integer from 0 to 15, and a set
  4986. of I<trace flags> that are either on or off. Together these are known
  4987. as the I<trace settings> and are stored together in a single integer.
  4988. For normal use you only need to set the trace level, and generally
  4989. only to a value between 1 and 4.
  4990. Each handle has it's own trace settings, and so does the DBI.
  4991. When you call a method the DBI merges the handles settings into its
  4992. own for the duration of the call: the trace flags of the handle are
  4993. OR'd into the trace flags of the DBI, and if the handle has a higher
  4994. trace level then the DBI trace level is raised to match it.
  4995. The previous DBI trace setings are restored when the called method
  4996. returns.
  4997. =head2 Trace Levels
  4998. Trace I<levels> are as follows:
  4999. 0 - Trace disabled.
  5000. 1 - Trace DBI method calls returning with results or errors.
  5001. 2 - Trace method entry with parameters and returning with results.
  5002. 3 - As above, adding some high-level information from the driver
  5003. and some internal information from the DBI.
  5004. 4 - As above, adding more detailed information from the driver.
  5005. 5 to 15 - As above but with more and more obscure information.
  5006. Trace level 1 is best for a simple overview of what's happening.
  5007. Trace level 2 is a good choice for general purpose tracing.
  5008. Levels 3 and above are best reserved for investigating a specific
  5009. problem, when you need to see "inside" the driver and DBI.
  5010. The trace output is detailed and typically very useful. Much of the
  5011. trace output is formatted using the L</neat> function, so strings
  5012. in the trace output may be edited and truncated by that function.
  5013. =head2 Trace Flags
  5014. Trace I<flags> are used to enable tracing of specific activities
  5015. within the DBI and drivers. The DBI defines some trace flags and
  5016. drivers can define others. DBI trace flag names begin with a capital
  5017. letter and driver specific names begin with a lowercase letter, as
  5018. usual.
  5019. Curently the DBI only defines two trace flags:
  5020. ALL - turn on all DBI and driver flags (not recommended)
  5021. SQL - trace SQL statements executed (not yet implemented)
  5022. The L</parse_trace_flags> and L</parse_trace_flag> methods are used
  5023. to convert trace flag names into the coresponding integer bit flags.
  5024. =head2 Enabling Trace
  5025. The C<$h-E<gt>trace> method sets the trace settings for a handle
  5026. and C<DBI-E<gt>trace> does the same for the DBI.
  5027. In addition to the L</trace> method, you can enable the same trace
  5028. information, and direct the output to a file, by setting the
  5029. C<DBI_TRACE> environment variable before starting Perl.
  5030. See L</DBI_TRACE> for more information.
  5031. Finally, you can set, or get, the trace settings for a handle using
  5032. the C<TraceLevel> attribute.
  5033. All of those methods use parse_trace_flags() and so allow you set
  5034. both the trace level and multiple trace flags by using a string
  5035. containing the trace level and/or flag names separated by vertical
  5036. bar ("C<|>") or comma ("C<,>") characters. For example:
  5037. local $h->{TraceLevel} = "3|SQL|foo";
  5038. =head2 Trace Output
  5039. Initially trace output is written to C<STDERR>. Both the
  5040. C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional
  5041. $trace_filename parameter. If specified, and can be opened in
  5042. append mode, then I<all> trace output (currently including that
  5043. from other handles) is redirected to that file. A warning is
  5044. generated if the file can't be opened.
  5045. Further calls to trace() without a $trace_filename do not alter where
  5046. the trace output is sent. If $trace_filename is undefined, then
  5047. trace output is sent to C<STDERR> and the previous trace file is closed.
  5048. Currently $trace_filename can't be a filehandle. But meanwhile you
  5049. can use the special strings C<"STDERR"> and C<"STDOUT"> to select
  5050. those filehandles.
  5051. =head2 Tracing Tips
  5052. You can add tracing to your own application code using the
  5053. L</trace_msg> method.
  5054. It can sometimes be handy to compare trace files from two different
  5055. runs of the same script. However using a tool like C<diff> doesn't work
  5056. well because the trace file is full of object addresses that may
  5057. differ each run. Here's a handy little command to strip those out:
  5058. perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}/<long number>/gi'
  5059. =head1 DBI ENVIRONMENT VARIABLES
  5060. The DBI module recognizes a number of environment variables, but most of
  5061. them should not be used most of the time.
  5062. It is better to be explicit about what you are doing to avoid the need
  5063. for environment variables, especially in a web serving system where web
  5064. servers are stingy about which environment variables are available.
  5065. =head2 DBI_DSN
  5066. The DBI_DSN environment variable is used by DBI->connect if you do not
  5067. specify a data source when you issue the connect.
  5068. It should have a format such as "dbi:Driver:databasename".
  5069. =head2 DBI_DRIVER
  5070. The DBI_DRIVER environment variable is used to fill in the database
  5071. driver name in DBI->connect if the data source string starts "dbi::"
  5072. (thereby omitting the driver).
  5073. If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap.
  5074. =head2 DBI_AUTOPROXY
  5075. The DBI_AUTOPROXY environment variable takes a string value that starts
  5076. "dbi:Proxy:" and is typically followed by "hostname=...;port=...".
  5077. It is used to alter the behaviour of DBI->connect.
  5078. For full details, see DBI::Proxy documentation.
  5079. =head2 DBI_USER
  5080. The DBI_USER environment variable takes a string value that is used as
  5081. the user name if the DBI->connect call is given undef (as distinct from
  5082. an empty string) as the username argument.
  5083. Be wary of the security implications of using this.
  5084. =head2 DBI_PASS
  5085. The DBI_PASS environment variable takes a string value that is used as
  5086. the password if the DBI->connect call is given undef (as distinct from
  5087. an empty string) as the password argument.
  5088. Be extra wary of the security implications of using this.
  5089. =head2 DBI_DBNAME (obsolete)
  5090. The DBI_DBNAME environment variable takes a string value that is used only when the
  5091. obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and
  5092. when no value is provided for the first (database name) argument.
  5093. =head2 DBI_TRACE
  5094. The DBI_TRACE environment variable specifies the global default
  5095. trace settings for the DBI at startup. Can also be used to direct
  5096. trace output to a file. When the DBI is loaded it does:
  5097. DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
  5098. So if C<DBI_TRACE> contains an "C<=>" character then what follows
  5099. it is used as the name of the file to append the trace to.
  5100. output appended to that file. If the name begins with a number
  5101. followed by an equal sign (C<=>), then the number and the equal sign are
  5102. stripped off from the name, and the number is used to set the trace
  5103. level. For example:
  5104. DBI_TRACE=1=dbitrace.log perl your_test_script.pl
  5105. On Unix-like systems using a Bourne-like shell, you can do this easily
  5106. on the command line:
  5107. DBI_TRACE=2 perl your_test_script.pl
  5108. See L</TRACING> for more information.
  5109. =head2 PERL_DBI_DEBUG (obsolete)
  5110. An old variable that should no longer be used; equivalent to DBI_TRACE.
  5111. =head2 DBI_PROFILE
  5112. The DBI_PROFILE environment variable can be used to enable profiling
  5113. of DBI method calls. See <DBI::Profile> for more information.
  5114. =head2 DBI_PUREPERL
  5115. The DBI_PUREPERL environment variable can be used to enable the
  5116. use of DBI::PurePerl. See <DBI::PurePerl> for more information.
  5117. =head1 WARNING AND ERROR MESSAGES
  5118. =head2 Fatal Errors
  5119. =over 4
  5120. =item Can't call method "prepare" without a package or object reference
  5121. The C<$dbh> handle you're using to call C<prepare> is probably undefined because
  5122. the preceding C<connect> failed. You should always check the return status of
  5123. DBI methods, or use the L</RaiseError> attribute.
  5124. =item Can't call method "execute" without a package or object reference
  5125. The C<$sth> handle you're using to call C<execute> is probably undefined because
  5126. the preceeding C<prepare> failed. You should always check the return status of
  5127. DBI methods, or use the L</RaiseError> attribute.
  5128. =item DBI/DBD internal version mismatch
  5129. The DBD driver module was built with a different version of DBI than
  5130. the one currently being used. You should rebuild the DBD module under
  5131. the current version of DBI.
  5132. (Some rare platforms require "static linking". On those platforms, there
  5133. may be an old DBI or DBD driver version actually embedded in the Perl
  5134. executable being used.)
  5135. =item DBD driver has not implemented the AutoCommit attribute
  5136. The DBD driver implementation is incomplete. Consult the author.
  5137. =item Can't [sg]et %s->{%s}: unrecognised attribute
  5138. You attempted to set or get an unknown attribute of a handle. Make
  5139. sure you have spelled the attribute name correctly; case is significant
  5140. (e.g., "Autocommit" is not the same as "AutoCommit").
  5141. =back
  5142. =head1 Pure-Perl DBI
  5143. A pure-perl emulation of the DBI is included in the distribution
  5144. for people using pure-perl drivers who, for whatever reason, can't
  5145. install the compiled DBI. See L<DBI::PurePerl>.
  5146. =head1 SEE ALSO
  5147. =head2 Driver and Database Documentation
  5148. Refer to the documentation for the DBD driver that you are using.
  5149. Refer to the SQL Language Reference Manual for the database engine that you are using.
  5150. =head2 ODBC and SQL/CLI Standards Reference Information
  5151. More detailed information about the semantics of certain DBI methods
  5152. that are based on ODBC and SQL/CLI standards is available on-line
  5153. via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI
  5154. standard:
  5155. DBI method ODBC function SQL/CLI Working Draft
  5156. ---------- ------------- ---------------------
  5157. column_info SQLColumns Page 124
  5158. foreign_key_info SQLForeignKeys Page 163
  5159. get_info SQLGetInfo Page 214
  5160. primary_key_info SQLPrimaryKeys Page 254
  5161. table_info SQLTables Page 294
  5162. type_info SQLGetTypeInfo Page 239
  5163. For example, for ODBC information on SQLColumns you'd visit:
  5164. http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp
  5165. If that URL ceases to work then use the MSDN search facility at:
  5166. http://search.microsoft.com/us/dev/
  5167. and search for C<SQLColumns returns> using the exact phrase option.
  5168. The link you want will probably just be called C<SQLColumns> and will
  5169. be part of the Data Access SDK.
  5170. And for SQL/CLI standard information on SQLColumns you'd read page 124 of
  5171. the (very large) SQL/CLI Working Draft available from:
  5172. http://www.jtc1sc32.org/sc32/jtc1sc32.nsf/Attachments/7E3B41486BD99C3488256B410064C877/$FILE/32N0744T.PDF
  5173. =head2 Standards Reference Information
  5174. A hyperlinked, browsable version of the BNF syntax for SQL92 (plus
  5175. Oracle 7 SQL and PL/SQL) is available here:
  5176. http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html
  5177. A BNF syntax for SQL3 is available here:
  5178. http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf
  5179. The following links provide further useful information about SQL.
  5180. Some of these are rather dated now but may still be useful.
  5181. http://www.jcc.com/SQLPages/jccs_sql.htm
  5182. http://www.contrib.andrew.cmu.edu/~shadow/sql.html
  5183. http://www.altavista.com/query?q=sql+tutorial
  5184. =head2 Books and Articles
  5185. Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
  5186. L<http://books.perl.org/book/154>
  5187. Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant.
  5188. L<http://books.perl.org/book/134>
  5189. Learning Perl by Randal Schwartz.
  5190. L<http://books.perl.org/book/101>
  5191. Details of many other books related to perl can be found at L<http://books.perl.org>
  5192. =head2 Perl Modules
  5193. Index of DBI related modules available from CPAN:
  5194. http://search.cpan.org/search?mode=module&query=DBIx%3A%3A
  5195. http://search.cpan.org/search?mode=doc&query=DBI
  5196. For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers
  5197. (including Class::DBI, Alzabo, and DBIx::RecordSet in the former
  5198. category and Tangram and SPOPS in the latter) see the Perl
  5199. Object-Oriented Persistence project pages at:
  5200. http://poop.sourceforge.net
  5201. A similar page for Java toolkits can be found at:
  5202. http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison
  5203. =head2 Mailing List
  5204. The I<dbi-users> mailing list is the primary means of communication among
  5205. users of the DBI and its related modules. For details send email to:
  5206. dbi-users-help@perl.org
  5207. There are typically between 700 and 900 messages per month. You have
  5208. to subscribe in order to be able to post. However you can opt for a
  5209. 'post-only' subscription.
  5210. Mailing list archives (of variable quality) are held at:
  5211. http://groups.google.com/groups?group=perl.dbi.users
  5212. http://www.xray.mpe.mpg.de/mailing-lists/dbi/
  5213. http://www.mail-archive.com/dbi-users%40perl.org/
  5214. =head2 Assorted Related WWW Links
  5215. The DBI "Home Page":
  5216. http://dbi.perl.org/
  5217. Other DBI related links:
  5218. http://tegan.deltanet.com/~phlip/DBUIdoc.html
  5219. http://dc.pm.org/perl_db.html
  5220. http://wdvl.com/Authoring/DB/Intro/toc.html
  5221. http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
  5222. http://bumppo.net/lists/macperl/1999/06/msg00197.html
  5223. http://gmax.oltrelinux.com/dbirecipes.html
  5224. Other database related links:
  5225. http://www.jcc.com/sql_stnd.html
  5226. http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
  5227. Security, especially the "SQL Injection" attack:
  5228. http://www.ngssoftware.com/research/papers.html
  5229. http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
  5230. http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
  5231. http://www.esecurityplanet.com/trends/article.php/2243461
  5232. http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf
  5233. http://www.webcohort.com/Blindfolded_SQL_Injection.pdf
  5234. http://online.securityfocus.com/infocus/1644
  5235. Commercial and Data Warehouse Links
  5236. http://www.dwinfocenter.org
  5237. http://www.datawarehouse.com
  5238. http://www.datamining.org
  5239. http://www.olapcouncil.org
  5240. http://www.idwa.org
  5241. http://www.knowledgecenters.org/dwcenter.asp
  5242. Recommended Perl Programming Links
  5243. http://language.perl.com/style/
  5244. =head2 FAQ
  5245. Please also read the DBI FAQ which is installed as a DBI::FAQ module.
  5246. You can use I<perldoc> to read it by executing the C<perldoc DBI::FAQ> command.
  5247. =head1 AUTHORS
  5248. DBI by Tim Bunce. This pod text by Tim Bunce, J. Douglas Dunlop,
  5249. Jonathan Leffler and others. Perl by Larry Wall and the
  5250. C<perl5-porters>.
  5251. =head1 COPYRIGHT
  5252. The DBI module is Copyright (c) 1994-2004 Tim Bunce. Ireland.
  5253. All rights reserved.
  5254. You may distribute under the terms of either the GNU General Public
  5255. License or the Artistic License, as specified in the Perl README file.
  5256. =head1 SUPPORT / WARRANTY
  5257. The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND.
  5258. =head2 Support
  5259. My consulting company, Data Plan Services, offers annual and
  5260. multi-annual support contracts for the DBI. These provide sustained
  5261. support for DBI development, and sustained value for you in return.
  5262. Contact me for details.
  5263. =head2 Sponsor Enhancements
  5264. The DBI Roadmap is available at L<http://search.cpan.org/~timb/DBI/Roadmap.pod>
  5265. If your company would benefit from a specific new DBI feature,
  5266. please consider sponsoring its development. Work is performed
  5267. rapidly, and usually on a fixed-price payment-on-delivery basis.
  5268. Contact me for details.
  5269. Using such targeted financing allows you to contribute to DBI
  5270. development, and rapidly get something specific and valuable in return.
  5271. =head1 ACKNOWLEDGEMENTS
  5272. I would like to acknowledge the valuable contributions of the many
  5273. people I have worked with on the DBI project, especially in the early
  5274. years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti,
  5275. Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler,
  5276. Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
  5277. Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
  5278. Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
  5279. Steve Baumgarten, Randal Schwartz, and a whole lot more.
  5280. Then, of course, there are the poor souls who have struggled through
  5281. untold and undocumented obstacles to actually implement DBI drivers.
  5282. Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
  5283. Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
  5284. Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
  5285. Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would
  5286. not be the practical reality it is today. I'm also especially grateful
  5287. to Alligator Descartes for starting work on the first edition of the
  5288. "Programming the Perl DBI" book and letting me jump on board.
  5289. The DBI and DBD::Oracle were originally developed while I was Technical
  5290. Director (CTO) of the Paul Ingram Group (www.ig.co.uk). So I'd
  5291. especially like to thank Paul for his generosity and vision in
  5292. supporting this work for many years.
  5293. =head1 CONTRIBUTING
  5294. As you can see above, many people have contributed to the DBI and
  5295. drivers in many ways over many years.
  5296. If you'd like to help then see L<http://dbi.perl.org/contributing>
  5297. and L<http://search.cpan.org/~timb/DBI/Roadmap.pod>
  5298. If you'd like the DBI to do something new or different then a good way
  5299. to make that happen is to do it yourself and send me a patch to the
  5300. source code that shows the changes. (But read "Speak before you patch"
  5301. below.)
  5302. =head2 Browsing the source code repository
  5303. Use http://svn.perl.org/modules/dbi/trunk (basic)
  5304. or http://svn.perl.org/viewcvs/modules/ (more useful)
  5305. =head2 How to create a patch using Subversion
  5306. The DBI source code is maintained using Subversion (a replacement
  5307. for CVS, see L<http://subversion.tigris.org/>). To access the source
  5308. you'll need to install a Subversion client. Then, to get the source
  5309. code, do:
  5310. svn checkout http://svn.perl.org/modules/dbi/trunk
  5311. If it prompts for a username and password use your perl.org account
  5312. if you have one, else just 'guest' and 'guest'. The source code will
  5313. be in a new subdirectory called C<trunk>.
  5314. To keep informed about changes to the source you can send an empty email
  5315. to dbi-changes@perl.org after which you'll get an email with the
  5316. change log message and diff of each change checked-in to the source.
  5317. After making your changes you can generate a patch file, but before
  5318. you do, make sure your source is still upto date using:
  5319. svn update
  5320. If you get any conflicts reported you'll need to fix them first.
  5321. Then generate the patch file from within the C<trunk> directory using:
  5322. svn diff > foo.patch
  5323. Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org.
  5324. =head2 How to create a patch without Subversion
  5325. Unpack a fresh copy of the distribution:
  5326. tar xfz DBI-1.40.tar.gz
  5327. Rename the newly created top level directory:
  5328. mv DBI-1.40 DBI-1.40.your_foo
  5329. Edit the contents of DBI-1.40.your_foo/* till it does what you want.
  5330. Test your changes and then remove all temporary files:
  5331. make test && make distclean
  5332. Go back to the directory you originally unpacked the distribution:
  5333. cd ..
  5334. Unpack I<another> copy of the original distribution you started with:
  5335. tar xfz DBI-1.40.tar.gz
  5336. Then create a patch file by performing a recursive C<diff> on the two
  5337. top level directories:
  5338. diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch
  5339. =head2 Speak before you patch
  5340. For anything non-trivial or possibly controversial it's a good idea
  5341. to discuss (on dbi-dev@perl.org) the changes you propose before
  5342. actually spending time working on them. Otherwise you run the risk
  5343. of them being rejected because they don't fit into some larger plans
  5344. you may not be aware of.
  5345. =head1 TRANSLATIONS
  5346. A German translation of this manual (possibly slightly out of date) is
  5347. available, thanks to O'Reilly, at:
  5348. http://www.oreilly.de/catalog/perldbiger/
  5349. Some other translations:
  5350. http://cronopio.net/perl/ - Spanish
  5351. http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
  5352. =head1 TRAINING
  5353. References to DBI related training resources. No recommendation implied.
  5354. http://www.treepax.co.uk/
  5355. http://www.keller.com/dbweb/
  5356. (If you offer professional DBI related training services,
  5357. please send me your details so I can add them here.)
  5358. =head1 FREQUENTLY ASKED QUESTIONS
  5359. See the DBI FAQ for a more comprehensive list of FAQs. Use the
  5360. C<perldoc DBI::FAQ> command to read it.
  5361. =head2 Why doesn't my CGI script work right?
  5362. Read the information in the references below. Please do I<not> post
  5363. CGI related questions to the I<dbi-users> mailing list (or to me).
  5364. http://www.perl.com/cgi-bin/pace/pub/doc/FAQs/cgi/perl-cgi-faq.html
  5365. http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
  5366. http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
  5367. http://www.boutell.com/faq/
  5368. http://www.perl.com/perl/faq/
  5369. =head2 How can I maintain a WWW connection to a database?
  5370. For information on the Apache httpd server and the C<mod_perl> module see
  5371. http://perl.apache.org/
  5372. =head1 OTHER RELATED WORK AND PERL MODULES
  5373. =over 4
  5374. =item Apache::DBI by E.Mergl@bawue.de
  5375. To be used with the Apache daemon together with an embedded Perl
  5376. interpreter like C<mod_perl>. Establishes a database connection which
  5377. remains open for the lifetime of the HTTP daemon. This way the CGI
  5378. connect and disconnect for every database access becomes superfluous.
  5379. =item JDBC Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au
  5380. The server is written in Perl. The client classes that talk to it are
  5381. of course in Java. Thus, a Java applet or application will be able to
  5382. comunicate via the JDBC API with any database that has a DBI driver installed.
  5383. The URL used is in the form C<jdbc:dbi://host.domain.etc:999/Driver/DBName>.
  5384. It seems to be very similar to some commercial products, such as jdbcKona.
  5385. =item Remote Proxy DBD support
  5386. As of DBI 1.02, a complete implementation of a DBD::Proxy driver and the
  5387. DBI::ProxyServer are part of the DBI distribution.
  5388. =item SQL Parser
  5389. See also the SQL::Statement module, SQL parser and engine.
  5390. =back
  5391. =cut