home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / DBD.pm < prev    next >
Encoding:
Perl POD Document  |  2004-01-07  |  102.4 KB  |  3,686 lines

  1. package DBI::DBD;
  2.  
  3. use vars qw($VERSION);    # set $VERSION early so we don't confuse PAUSE/CPAN etc
  4.  
  5. $VERSION = sprintf("%d.%02d", q$Revision: 11.20 $ =~ /(\d+)\.(\d+)/o);
  6.  
  7.  
  8. # $Id: DBD.pm,v 11.20 2004/01/07 17:38:51 timbo Exp $
  9. #
  10. # Copyright (c) 1997-2003 Jonathan Leffler, Jochen Wiedmann, Steffen
  11. # Goeldner and Tim Bunce
  12. #
  13. # You may distribute under the terms of either the GNU General Public
  14. # License or the Artistic License, as specified in the Perl README file.
  15.  
  16. ########################################################################
  17. # JL 2002-12-30 - Ouch!
  18. # NB: In Perl 5.6.x and earlier, POD only supports =head1 and =head2,
  19. # whereas in Perl 5.8.0 and later, POD supports =head3 and =head4 too.
  20. # This document reads better in HTML if =head3 and =head4 are used.
  21. # To convert this document to Perl 5.8.0 POD markup, run this script:
  22. #
  23. ##!/bin/perl -w
  24. ##
  25. ## Remove Perl 5.6.x and earlier POD markup, leaving Perl 5.8.0 POD
  26. ## markup (=head3, =head4) visible.
  27. #
  28. #while (<>)
  29. #{
  30. #    if (m/^#=POD-Perl-5.6.x=begin/o)
  31. #    {
  32. #        while (<>)
  33. #        {
  34. #            last if m/^#=POD-Perl-5.6.x=end/o;
  35. #        }
  36. #        next;
  37. #    }
  38. #    elsif (m/^#=head[34]\s/o)
  39. #    {
  40. #        s/^#//o;
  41. #        $_ = "=pod\n\n$_\n=cut\n\n";
  42. #    }
  43. #    print $_;
  44. #}
  45. #
  46. # NBB: POD does not provide a mechanism for embedding comments in POD
  47. # material.  Hence the convoluted =cut, # comments, and =pod directives
  48. # (which are supported as far back as Perl 5.005_03).
  49. ########################################################################
  50.  
  51. =head1 NAME
  52.  
  53. DBI::DBD - Perl DBI Database Driver Writer's Guide
  54.  
  55. =head1 SYNOPSIS
  56.  
  57.   perldoc DBI::DBD
  58.  
  59. =head2 Version and volatility
  60.  
  61.   $Revision: 11.20 $
  62.   $Date: 2004/01/07 17:38:51 $
  63.  
  64. This document is I<still> a minimal draft which is in need of further work.
  65.  
  66. The changes will occur both because the DBI specification is changing
  67. and hence the requirements on DBD drivers change, and because feedback
  68. from people reading this document will suggest improvements to it.
  69.  
  70. Please read the DBI documentation first and fully, including the DBI FAQ.
  71. Then reread the DBI specification again as you're reading this. It'll help.
  72.  
  73. This document is a patchwork of contributions from various authors.
  74. More contributions (preferably as patches) are very welcome.
  75.  
  76. =head1 DESCRIPTION
  77.  
  78. This document is primarily intended to help people writing new
  79. database drivers for the Perl Database Interface (Perl DBI).
  80. It may also help others interested in discovering why the internals of
  81. a DBD driver are written the way they are.
  82.  
  83. This is a guide.  Few (if any) of the statements in it are completely
  84. authoritative under all possible circumstances.  This means you will
  85. need to use judgement in applying the guidelines in this document.
  86. If in I<any> doubt at all, please do contact the dbi-dev mailing list
  87. (details given below) where Tim Bunce and other driver authors can help.
  88.  
  89. =head1 CREATING A NEW DRIVER
  90.  
  91. The first rule for creating a new database driver for the Perl DBI is
  92. very simple: "DON'T!"
  93.  
  94. There is usually a driver already available for the database you want to
  95. use, almost regardless of which database you choose.
  96. And very often, the database will provide an ODBC driver interface, so
  97. you can often use DBD::ODBC to access the database.
  98. This is typically less convenient on a Unix box than on a Microsoft
  99. Windows box, but there are numerous options for ODBC driver managers on
  100. Unix too, and very often the ODBC driver is provided by the database
  101. supplier.
  102. Before deciding that you need to write a driver, do your homework to
  103. ensure that you are not wasting your energies.
  104.  
  105. [As of December 2002, the consensus is that if you need an ODBC driver
  106. manager on Unix, then the unixODBC driver (available from
  107. L<http://www.unixodbc.org/>) is the way to go.]
  108.  
  109. The second rule for creating a new database driver for the Perl DBI is
  110. also very simple: "Don't -- get someone else to do it for you!"
  111.  
  112. Nevertheless, there are occasions when it is necessary to write a new
  113. driver, often to use a proprietary language or API to access the
  114. database more swiftly, or more comprehensively, than an ODBC driver can.
  115. Then you should read this document very carefully, but with a suitably
  116. sceptical eye.
  117. If there is something in here that does not make any sense, question it.
  118. You might be right that the information is bogus.
  119. But don't come to that conclusion too quickly.
  120.  
  121. =head2 URLs and mailing lists
  122.  
  123. The primary web-site for locating DBI software and information is
  124.  
  125.   http://dbi.perl.org/
  126.  
  127. There are two main and one auxilliary mailing lists for people working
  128. with DBI.  The primary lists are dbi-users@perl.org for general users
  129. of DBI and DBD drivers, and dbi-dev@perl.org mainly for DBD driver
  130. writers (don't join the dbi-dev list unless you have a good reason).
  131. The auxilliary list is dbi-announce@perl.org for announcing new
  132. releases of DBI or DBD drivers.
  133.  
  134. You can join these lists by accessing the web-site
  135. L<http://dbi.perl.org/>.
  136. The lists are closed so you cannot send email to any of the lists
  137. unless you join the list first.
  138.  
  139. You should also consider monitoring the comp.lang.perl.* newsgroups,
  140. especially comp.lang.perl.modules.
  141.  
  142. =head2 The Cheetah book
  143.  
  144. The definitive book on Perl DBI is the Cheetah book, so called because
  145. of the picture on the cover.
  146. Its proper title is 'Programming the Perl DBI: Database programming with
  147. Perl' by Alligator Descartes and Tim Bunce, published by O'Reilly
  148. Associates, February 2000, ISBN 1-56592-699-4.
  149. Buy it now if you have not already done so, and read it.
  150.  
  151. =head2 Locating drivers
  152.  
  153. Before writing a new driver, it is in your interests to find out
  154. whether there already is a driver for your database.  If there is such
  155. a driver, it would be much easier to make use of it than to write your
  156. own!
  157.  
  158. The primary web-site for locating Perl software is
  159. L<http://search.cpan.org/>.  You should look under the various
  160. modules listings for the software you are after. For example:
  161.  
  162.   http://search.cpan.org/modlist/Database_Interfaces
  163.  
  164. Follow the DBD:: and DBIx:: links at the top to see those subsets.
  165.  
  166. See the DBI docs for information on DBI web sites and mailing lists.
  167.  
  168. =head2 Registering a new driver
  169.  
  170. Before going through any official registration process, you will need
  171. to establish that there is no driver already in the works.
  172. You'll do that by asking the DBI mailing lists whether there is such a
  173. driver available, or whether anybody is working on one.
  174.  
  175. When you get the go ahead, you will need to establish the name of the
  176. driver and a prefix for the driver.
  177. Typically, the name is based on the name of the database software it
  178. uses, and the prefix is a contraction of that.
  179. Hence, DBD::Oracle has the name Oracle and the prefix 'ora_'.
  180. This information will be recorded in the DBI documentation.
  181.  
  182. This document assumes you are writing a driver called DBD::Driver, and
  183. that the prefix 'drv_' is assigned to the driver.
  184.  
  185. =head2 Two styles of database driver
  186.  
  187. There are two distinct styles of database driver that can be written to
  188. work with the Perl DBI.
  189.  
  190. Your driver can be written in pure Perl, requiring no C compiler.
  191. When feasible, this is the best solution, but most databases are not
  192. written in such a way that this can be done.
  193. Some example pure Perl drivers are DBD::File and DBD::CSV.
  194.  
  195. Alternatively, and most commonly, your driver will need to use some C
  196. code to gain access to the database.
  197. This will be classified as a C/XS driver.
  198.  
  199. =head2 What code will you write?
  200.  
  201. There are a number of files that need to be written for either a pure
  202. Perl driver or a C/XS driver.
  203. There are no extra files needed only by a pure Perl driver, but there are
  204. several extra files needed only by a C/XS driver.
  205.  
  206. =cut
  207.  
  208. #=head3 Files common to pure Perl and C/XS drivers
  209. #=POD-Perl-5.6.x=begin
  210.  
  211. =pod
  212.  
  213. =over 2
  214.  
  215. =item Files common to pure Perl and C/XS drivers
  216.  
  217. =cut
  218.  
  219. #=POD-Perl-5.6.x=end
  220.  
  221. =pod
  222.  
  223. Assuming that your driver is called DBD::Driver, these files are:
  224.  
  225. =over 4
  226.  
  227. =item Makefile.PL
  228.  
  229. =item README
  230.  
  231. =item MANIFEST
  232.  
  233. =item Driver.pm
  234.  
  235. =item lib/Bundle/DBD/Driver.pm
  236.  
  237. =item lib/DBD/Driver/Summary.pm
  238.  
  239. =item t/*.t
  240.  
  241. =back
  242.  
  243. Needless to say, all these files are either text files or pure Perl.
  244.  
  245. The first four files are mandatory.
  246. Makefile.PL is used to control how the driver is built and installed.
  247. The README file tells people who download the file about how to build
  248. the module and any prerequisite software that must be installed.
  249. The MANIFEST file is used by the standard Perl module distribution mechanism.
  250. It lists all the source files that need to be distributed with your module.
  251. Driver.pm is what is loaded by the DBI code; it contains the methods
  252. peculiar to your driver.
  253.  
  254. The lib/Bundle/DBD/Driver.pm file allows you to specify other Perl
  255. modules on which yours depends in a format that allows someone to type a
  256. simple command and ensure that all the pre-requisites are in place as
  257. well as building your driver.
  258. The lib/DBD/Driver/Summary.pm file contains (an updated version of) the
  259. information that was included - or that would have been included - in
  260. the appendices of the Cheetah book as a summary of the abilities of your
  261. driver and the associated database.
  262.  
  263. The files in the t subdirectory are unit tests for your driver.
  264. You should write your tests as stringently as possible, while taking
  265. into account the diversity of installations that you can encounter.
  266. Your tests should not casually modify operational databases.
  267. You should never damage existing tables in a database.
  268. You should code your tests to use a constrained name space within the
  269. database.
  270. For example, the tables (and all other named objects) that are created
  271. could all begin with 'dbd_drv_'.
  272. At the end of a test run, there should be no testing objects left behind
  273. in the database.
  274. If you create any databases, you should remove them.
  275. If your database supports temporary tables that are automatically
  276. removed at the end of a session, then exploit them as often as possible.
  277. Try to make your tests independent of each other.
  278. If you have a test t/t11dowhat.t that depends upon the successful
  279. running of t/t10thingamy.t, people cannot run the single test case
  280. t/t11dowhat.t.
  281. Further, running t/t11dowhat.t twice in a row is likely to fail (at
  282. least, if t/t11dowhat.t modifies the database at all) because the
  283. database at the start of the second run is not what you saw at the start
  284. of the first run.
  285. Document in your README file what you do, and what privileges people
  286. need to do it.
  287. You can, and probably should, sequence your tests by including a test
  288. number before an abbreviated version of the test name; the tests are run
  289. in the order in which the names are expanded by shell-style globbing.
  290.  
  291. Many drivers also install sub-modules DBD::Driver::SubModule for any of
  292. a variety of different reasons, such as to support the metadata methods
  293. (see the discussion of L</METADATA METHODS> below).
  294. Such sub-modules are conventionally stored in the directory lib/DBD/Driver.
  295. The module itself would usually be in a file SubModule.pm.
  296. All such sub-modules should themselves be version stamped (see the
  297. discussions far below).
  298.  
  299. =cut
  300.  
  301. #=head3 Extra files needed by C/XS drivers
  302. #=POD-Perl-5.6.x=begin
  303.  
  304. =pod
  305.  
  306. =back
  307.  
  308. =over 2
  309.  
  310. =item Extra files needed by C/XS drivers
  311.  
  312. =cut
  313.  
  314. #=POD-Perl-5.6.x=end
  315.  
  316. =pod
  317.  
  318. The software for a C/XS driver will typically contain at least four
  319. extra files that are not relevant to a pure Perl driver.
  320.  
  321. =over 4
  322.  
  323. =item Driver.xs
  324.  
  325. =item Driver.h
  326.  
  327. =item dbdimp.h
  328.  
  329. =item dbdimp.c
  330.  
  331. =back
  332.  
  333. The Driver.xs file is used to generate C code that Perl can call to gain
  334. access to the C functions you write that will, in turn, call down onto
  335. your database software.
  336. The Driver.h header is a stylized header that ensures you can access the
  337. necessary Perl and DBI macros, types, and function declarations.
  338. The dbdimp.h is used to specify which functions have been implemented by
  339. your driver.
  340. The dbdimp.c file is where you write the C code that does the real work
  341. of translating between Perl-ish data types and what the database expects
  342. to use and return.
  343.  
  344. There are some (mainly small, but very important) differences between
  345. the contents of Makefile.PL and Driver.pm for pure Perl and C/XS
  346. drivers, so those files are described both in the section on creating a
  347. pure Perl driver and in the section on creating a C/XS driver.
  348.  
  349. Obviously, you can add extra source code files to the list.
  350.  
  351. =cut
  352.  
  353. #=POD-Perl-5.6.x=begin
  354.  
  355. =pod
  356.  
  357. =back
  358.  
  359. =cut
  360.  
  361. #=POD-Perl-5.6.x=end
  362.  
  363. =pod
  364.  
  365. =head2 Requirements on a driver and driver writer
  366.  
  367. To be remotely useful, your driver must be implemented in a format that
  368. allows it to be distributed via CPAN, the Comprehensive Perl Archive
  369. Network (http://www.cpan.org/ and http://search.cpan.org).
  370. Of course, it is easier if you do not have to meet this criterion, but
  371. you will not be able to ask for much help if you do not do so, and
  372. no-one is likely to want to install your module if they have to learn a
  373. new installation mechanism.
  374.  
  375. =head1 CREATING A PURE PERL DRIVER
  376.  
  377. Writing a pure Perl driver is surprisingly simple. However, there are
  378. some problems you should be aware of. The best option is of course
  379. picking up an existing driver and carefully modifying one method
  380. after the other.
  381.  
  382. Also look carefully at DBD::AnyData and DBD::Template.
  383.  
  384. As an example we take a look at the I<DBD::File> driver, a driver for
  385. accessing plain files as tables, which is part of the I<DBD::CSV>
  386. package.
  387. In what follows I assume the name C<Driver> for your new package and the
  388. prefix 'drv_'.
  389. The minimal set of files we have to implement are I<Makefile.PL>,
  390. I<README>, I<MANIFEST> and I<Driver.pm>.
  391. Files in the 'nice to have' category include '
  392.  
  393. =head2 Pure Perl version of Makefile.PL
  394.  
  395. You typically start with writing C<Makefile.PL>, a Makefile generator.
  396. The contents of this file are described in detail in the
  397. C<ExtUtils::MakeMaker> man pages.
  398. It is definitely a good idea if you start reading them.
  399. At least you should know about the variables I<CONFIGURE>, I<DEFINED>,
  400. I<PM>, I<DIR>, I<EXE_FILES>, I<INC>, I<LIBS>, I<LINKTYPE>, I<NAME>,
  401. I<OPTIMIZE>, I<PL_FILES>, I<VERSION>, I<VERSION_FROM>, I<clean>,
  402. I<depend>, I<realclean> from the C<ExtUtils::MakeMaker> man page: These
  403. are used in almost any Makefile.PL.
  404. Additionally read the section on I<Overriding MakeMaker Methods> and the
  405. descriptions of the I<distcheck>, I<disttest> and I<dist> targets: They
  406. will definitely be useful for you.
  407.  
  408. Of special importance for DBI drivers is the I<postamble> method from
  409. the C<ExtUtils::MM_Unix> man page.
  410. And, for Emacs users, I recommend the I<libscan> method, which removes
  411. Emacs backup files (file names which end with a tilde '~') from lists of
  412. files.
  413.  
  414. Now an example, I use the word C<Driver> wherever you should insert
  415. your driver's name:
  416.  
  417.   # -*- perl -*-
  418.  
  419.   use DBI 1.03;
  420.   use DBI::DBD;
  421.   use ExtUtils::MakeMaker;
  422.  
  423.   WriteMakefile(
  424.       dbd_edit_mm_attribs( {
  425.           'NAME'         => 'DBD::Driver',
  426.           'VERSION_FROM' => 'Driver.pm',
  427.           'INC'          => $DBI_INC_DIR,
  428.           'dist'         => { 'SUFFIX'   => '.gz',
  429.                               'COMPRESS' => 'gzip -9f' },
  430.           'realclean'    => { FILES => '*.xsi' },
  431.       },
  432.       { create_pp_tests => 1})
  433.   );
  434.  
  435.   package MY;
  436.   sub postamble { return main::dbd_postamble(@_); }
  437.   sub libscan {
  438.       my ($self, $path) = @_;
  439.       ($path =~ m/\~$/) ? undef : $path;
  440.   }
  441.  
  442. Note the calls to C<dbd_edit_mm_attribs>() and C<dbd_postamble>().
  443. The second hash reference in the call to C<dbd_edit_mm_attribs>
  444. (containing C<create_pp_tests>) is optional; you should not use it
  445. unless your driver is a pure Perl driver (that is, it does not use C and
  446. XS code).
  447. Therefore, the call to C<dbd_edit_mm_attribs> is not relevant for C/XS
  448. drivers and may be omitted; simply use the (single) hash reference
  449. containing NAME etc as the only argument to C<WriteMakefile>().
  450. Note that the C<dbd_edit_mm_attribs> code will fail if you do not have a
  451. C<t> sub-directory containing at least one test case.
  452. All drivers must use C<dbd_postamble> or risk running into problems.
  453.  
  454. Note the specification of VERSION_FROM; the named file (Driver.pm) will
  455. be scanned for the first line that looks like an assignment to $VERSION,
  456. and the subsequent text will be used to determine the version number.
  457. Note the commentary in L<ExtUtils::MakeMaker> on the subject of
  458. correctly formatted version numbers.
  459.  
  460. If your driver depends upon external software (it usually will), you
  461. will need to add code to ensure that your environment is workable before
  462. the call to C<WriteMakefile>().
  463. A full-fledged Makefile.PL can be quite large (for example, the files
  464. for DBD::Oracle and DBD::Informix are both over 1000 lines long, and the
  465. Informix one uses - and creates - auxilliary modules too).
  466.  
  467. See also L<ExtUtils::MakeMaker(3)> and L<ExtUtils::MM_Unix(3)>.
  468. Consider using L<CPAN::MakeMaker(3)> in place of ExtUtils::MakeMaker.
  469.  
  470. =head2 README
  471.  
  472. The README file should describe what the driver is for, the
  473. pre-requisites for the build process, the actual build process, how to
  474. report errors, and who to report them to.
  475. Users will find ways of breaking the driver build and test process which
  476. you would never even have dreamed to be possible in your worst
  477. nightmares.
  478. Therefore, you need to write this document defensively, precisely and
  479. concisely.
  480. Also, it is in your interests to ensure that your tests work as widely
  481. as possible.
  482. As always, use the README from one of the established drivers as a basis
  483. for your own; the version in DBD::Informix is worth a look as it has
  484. been quite successful in heading off problems.
  485.  
  486. =over 2
  487.  
  488. =item *
  489.  
  490. Note that users will have versions of Perl and DBI that are both older
  491. and newer than you expected, but this will seldom cause much trouble.
  492. When it does, it will be because you are using features of DBI that are
  493. not supported in the version they are using.
  494.  
  495. =item *
  496.  
  497. Note that users will have versions of the database software that are
  498. both older and newer than you expected.
  499. You will save yourself time in the long run if you can identify the
  500. range of versions which have been tested and warn about versions which
  501. are not known to be OK.
  502.  
  503. =item *
  504.  
  505. Note that many people trying to install your driver will not be experts
  506. in the database software.
  507.  
  508. =item *
  509.  
  510. Note that many people trying to install your driver will not be experts
  511. in C or Perl.
  512.  
  513. =back
  514.  
  515. =head2 MANIFEST
  516.  
  517. The MANIFEST will be used by the Makefile's dist target to build the
  518. distribution tar file that is uploaded to CPAN. It should list every
  519. file that you want to include in your distribution, one per line.
  520.  
  521. =head2 lib/Bundle/DBD/Driver.pm
  522.  
  523. The CPAN module provides an extremely powerful bundle mechanism that
  524. allows you to specify pre-requisites for your driver.
  525. The primary pre-requisite is Bundle::DBI; you may want or need to add
  526. some more.
  527. With the bundle set up correctly, the user can type:
  528.  
  529.         perl -MCPAN -e 'install Bundle::DBD::Driver'
  530.  
  531. and Perl will download, compile, test and install all the Perl modules
  532. needed to build your driver.
  533.  
  534. A suitable skeleton for this file is shown below.
  535. The prerequisite modules are listed in the C<CONTENTS> section, with the
  536. official name of the module followed by a dash and an informal name or
  537. description.
  538. Listing Bundle::DBI as the main pre-requisite simplifies life.
  539. Don't forget to list your driver.
  540. Note that unless the DBMS is itself a Perl module, you cannot list it as
  541. a pre-requisite in this file.
  542. You should keep the version of the bundle the same as the version of
  543. your driver.
  544. You should add configuration management, copyright, and licencing
  545. information at the top.
  546.  
  547.   package Bundle::DBD::Driver;
  548.  
  549.   $VERSION = '0.01';
  550.  
  551.   1;
  552.  
  553.   __END__
  554.  
  555.   =head1 NAME
  556.  
  557.   Bundle::DBD::Driver - A bundle to install all DBD::Driver related modules
  558.  
  559.   =head1 SYNOPSIS
  560.  
  561.   C<perl -MCPAN -e 'install Bundle::DBD::Driver'>
  562.  
  563.   =head1 CONTENTS
  564.  
  565.   Bundle::DBI  - Bundle for DBI by TIMB (Tim Bunce)
  566.  
  567.   DBD::Driver  - DBD::Driver by YOU (Your Name)
  568.  
  569.   =head1 DESCRIPTION
  570.  
  571.   This bundle includes all the modules used by the Perl Database
  572.   Interface (DBI) driver for Driver (DBD::Driver), assuming the
  573.   use of DBI version 1.13 or later, created by Tim Bunce.
  574.  
  575.   If you've not previously used the CPAN module to install any
  576.   bundles, you will be interrogated during its setup phase.
  577.   But when you've done it once, it remembers what you told it.
  578.   You could start by running:
  579.  
  580.     C<perl -MCPAN -e 'install Bundle::CPAN'>
  581.  
  582.   =head1 SEE ALSO
  583.  
  584.   Bundle::DBI
  585.  
  586.   =head1 AUTHOR
  587.  
  588.   Your Name E<lt>F<you@yourdomain.com>E<gt>
  589.  
  590.   =head1 THANKS
  591.  
  592.   This bundle was created by ripping off Bundle::libnet created by
  593.   Graham Barr E<lt>F<gbarr@ti.com>E<gt>, and radically simplified
  594.   with some information from Jochen Wiedmann E<lt>F<joe@ispsoft.de>E<gt>.
  595.   The template was then included in the DBI::DBD documentation by
  596.   Jonathan Leffler E<lt>F<jleffler@informix.com>E<gt>.
  597.  
  598.   =cut
  599.  
  600. =head2 lib/DBD/Driver/Summary.pm
  601.  
  602. There is no substitute for taking the summary file from a driver that
  603. was documented in the Perl book (such as DBD::Oracle or DBD::Informix or
  604. DBD::ODBC, to name but three), and adapting it to describe the
  605. facilities available via DBD::Driver when accessing the Driver database.
  606.  
  607. =head2 Pure Perl version of Driver.pm
  608.  
  609. The C<Driver.pm> file defines the Perl module DBD::Driver for your driver.
  610. It will define a package DBD::Driver along with some version information,
  611. some variable definitions, and a function driver() which will have a more
  612. or less standard structure.
  613.  
  614. It will also define three sub-packages of DBD::Driver:
  615.  
  616. =over 2
  617.  
  618. =item DBD::Driver::dr
  619.  
  620. with methods connect(), data_sources() and disconnect_all();
  621.  
  622. =item DBD::Driver::db
  623.  
  624. with methods such as prepare();
  625.  
  626. =item DBD::Driver::st
  627.  
  628. with methods such as execute() and fetch().
  629.  
  630. =back
  631.  
  632. The Driver.pm file will also contain the documentation specific to
  633. DBD::Driver in the format used by perldoc.
  634.  
  635. In a pure Perl driver, the Driver.pm file is the core of the
  636. implementation.
  637. You will need to provide all the key methods needed by DBI.
  638.  
  639. Now let's take a closer look at an excerpt of File.pm as an example.
  640. We ignore things that are common to any module (even non-DBI modules)
  641. or really specific to the DBD::File package.
  642.  
  643. =cut
  644.  
  645. #=head3 The DBD::Driver package
  646. #=POD-Perl-5.6.x=begin
  647.  
  648. =pod
  649.  
  650. =over 2
  651.  
  652. =item The DBD::Driver package
  653.  
  654. =cut
  655.  
  656. #=POD-Perl-5.6.x=end
  657.  
  658. =pod
  659.  
  660. =cut
  661.  
  662. #=head4 The header
  663. #=POD-Perl-5.6.x=begin
  664.  
  665. =pod
  666.  
  667. =back
  668.  
  669. =over 2
  670.  
  671. =item The header
  672.  
  673. =cut
  674.  
  675. #=POD-Perl-5.6.x=end
  676.  
  677. =pod
  678.  
  679.   package DBD::File;
  680.  
  681.   use strict;
  682.   use vars qw($err $errstr $state $drh);
  683.  
  684.   $err = 0;             # holds error code   for DBI::err
  685.   $errstr = "";         # holds error string for DBI::errstr
  686.   $sqlstate = "S1000";  # holds SQL state    for DBI::state
  687.  
  688. These variables are used for storing error states and messages.
  689. Note that most pure Perl drivers do not support the SQL standard error
  690. indicator SQLSTATE, and for such drivers, the value "S1000" is
  691. appropriate.
  692. If your database does support SQLSTATE, then initialize $sqlstate to an
  693. empty string.
  694. However, it is crucial to understand that you must not modify them
  695. directly; see below.
  696.  
  697.   $VERSION = "1.23.00"  # Version number of DBD::File
  698.  
  699. This is where the version number of your driver is specified.
  700. The code in Makefile.PL is told to look in this file for the
  701. information.
  702. It is recommended that you use a two-part (1.23) or three-part (1.23.45)
  703. version number.
  704. Please ensure that any other modules added with your driver are also
  705. version stamped so that CPAN does not get confused.
  706. Also consider the CPAN system, which gets confused and considers
  707. version 1.10 to precede version 1.9, so that using a raw CVS, RCS or
  708. SCCS version number is probably not appropriate (despite being very
  709. common). For RCS or CVS you can use this code:
  710.  
  711.   $VERSION = sprintf "%d.%02d", '$Revision: 11.20 $ ' =~ /(\d+)\.(\d+)/;
  712.  
  713. which pads out the fractional part with leading zeros so all is well
  714. (so long as you don't go past x.99)
  715.  
  716.   $drh = undef;         # holds driver handle once initialized
  717.  
  718. This is where the driver handle will be stored, once created.
  719. Note that you may assume there is only one handle for your driver.
  720.  
  721. =cut
  722.  
  723. #=head4 The driver constructor
  724. #=POD-Perl-5.6.x=begin
  725.  
  726. =pod
  727.  
  728. =back
  729.  
  730. =over 2
  731.  
  732. =item The driver constructor
  733.  
  734. =cut
  735.  
  736. #=POD-Perl-5.6.x=end
  737.  
  738. =pod
  739.  
  740. Note that the I<driver> method is in the DBD::Driver package, not in one
  741. of the sub-packages DBD::Driver::dr, DBD::Driver::db, or
  742. DBD::Driver::db.
  743.  
  744.   sub driver
  745.   {
  746.       return $drh if $drh;      # already created - return same one
  747.       my ($class, $attr) = @_;
  748.  
  749.       $class .= "::dr";
  750.  
  751.       # not a 'my' since we use it above to prevent multiple drivers
  752.       $drh = DBI::_new_drh($class, {
  753.               'Name'        => 'File',
  754.               'Version'     => $VERSION,
  755.               'Attribution' => 'DBD::File by Jochen Wiedmann',
  756.           })
  757.           or return undef;
  758.  
  759.       return $drh;
  760.   }
  761.  
  762. The I<driver> method is the driver handle constructor. It's a
  763. reasonable example of how DBI implements its handles. There are three
  764. kinds: B<driver handles> (typically stored in C<$drh>; from now on
  765. called C<drh> of C<$drh>), B<database handles> (from now on called C<dbh> or
  766. C<$dbh>) and B<statement handles> (from now on called C<sth> or
  767. C<$sth>).
  768.  
  769. The prototype of DBI::_new_drh is
  770.  
  771.   $drh = DBI::_new_drh($class, $public_attrs, $private_attrs);
  772.  
  773. with the following arguments:
  774.  
  775. =over 4
  776.  
  777. =item I<$class>
  778.  
  779. is typically the class for your driver, (for example, "DBD::File::dr"),
  780. passed as the first argument to the I<driver> method.
  781.  
  782. =item I<$public_attrs>
  783.  
  784. is a hash ref to attributes like I<Name>, I<Version>, and I<Attribution>.
  785. These are processed and used by DBI.
  786. You had better not make any assumptions about them nor should you add
  787. private attributes here.
  788.  
  789. =item I<$private_attrs>
  790.  
  791. This is another (optional) hash ref with your private attributes.
  792. DBI will store them and otherwise leave them alone.
  793.  
  794. =back
  795.  
  796. The I<DBI::new_drh> method and the I<driver> method both return C<undef>
  797. for failure (in which case you must look at $DBI::err and $DBI::errstr
  798. for the failure information, because you have no driver handle to use).
  799.  
  800. Also needed here, in the DBD::Driver package, is a CLONE() method
  801. that will be called by perl when an intrepreter is cloned. All your
  802. CLONE method needs to do, currently, is clear the cached $drh so
  803. the new interpreter won't start using the cached $drh from the old
  804. interpreter:
  805.  
  806.   sub CLONE {
  807.     undef $rdh;
  808.   }
  809.  
  810. =cut
  811.  
  812. #=head3 The DBD::Driver::dr package
  813. #=POD-Perl-5.6.x=begin
  814.  
  815. =pod
  816.  
  817. =back
  818.  
  819. =over 2
  820.  
  821. =item The DBD::Driver::dr package
  822.  
  823. =cut
  824.  
  825. #=POD-Perl-5.6.x=end
  826.  
  827. =pod
  828.  
  829. =cut
  830.  
  831. #=head4 The database handle constructor
  832. #=POD-Perl-5.6.x=begin
  833.  
  834. =pod
  835.  
  836. =back
  837.  
  838. =over 2
  839.  
  840. =item The database handle constructor
  841.  
  842. =cut
  843.  
  844. #=POD-Perl-5.6.x=end
  845.  
  846. =pod
  847.  
  848. The next lines of code look as follows:
  849.  
  850.   package DBD::Driver::dr; # ====== DRIVER ======
  851.  
  852.   $DBD::Driver::dr::imp_data_size = 0;
  853.  
  854. Note that no @ISA is needed here, or for the other DBD::Driver::*
  855. classes, because the DBI takes care of that for you when the driver is
  856. loaded.
  857.  
  858. The database handle constructor is a driver method, thus we have
  859. to change the namespace.
  860.  
  861.   sub connect
  862.   {
  863.       my ($drh, $dbname, $user, $auth, $attr) = @_;
  864.  
  865.       # Some database specific verifications, default settings
  866.       # and the like can go here. This should only include
  867.       # syntax checks or similar stuff where it's legal to
  868.       # 'die' in case of errors.
  869.       # For example, many database packages requires specific
  870.       # environment variables to be set; this could be where you
  871.       # validate that they are set, or default them if they are not set.
  872.  
  873.       # create a 'blank' dbh (call superclass constructor)
  874.       my $dbh = DBI::_new_dbh($drh, {
  875.               'Name'         => $dbname,
  876.           })
  877.           or return undef;
  878.  
  879.       # Process attributes from the DSN; we assume ODBC syntax
  880.       # here, that is, the DSN looks like var1=val1;...;varN=valN
  881.       foreach my $var (split(/;/, $dbname)) {
  882.           if ($var =~ m/(.*?)=(,*)/) {
  883.               # Not !!! $dbh->{$var} = $val;
  884.               $dbh->STORE($var, $val);
  885.           }
  886.       }
  887.       $dbh;
  888.   }
  889.  
  890. The Name attribute is a standard DBI attribute.
  891.  
  892. This is mostly the same as in the I<driver handle constructor> above.
  893. The arguments are described in the DBI man page.
  894. See L<DBI(3)>.
  895. The constructor _new_dbh is called, returning a database handle.
  896. The constructor's prototype is:
  897.  
  898.   $dbh = DBI::_new_dbh($drh, $public_attr, $private_attr);
  899.  
  900. with similar arguments to those in the I<driver handle constructor>,
  901. except that the C<$class> is replaced by C<$drh>.
  902.  
  903. Note the use of the I<STORE> method for setting the dbh attributes.
  904. That's because within the driver code, the handle object you have is
  905. the 'inner' handle of a tied hash, not the outer handle that the
  906. users of your driver have.
  907.  
  908. Because you have the inner handle, tie magic doesn't get invoked
  909. when you get or set values in the hash. This is often very handy for
  910. speed when you want to get or set simple non-special driver-specific
  911. attributes.
  912.  
  913. However, some attribute values, such as those handled by the DBI
  914. like PrintError, don't actually exist in the hash and must be
  915. read via $h->FETCH($attrib) and set via $h->STORE($attrib, $value).
  916. If in any doubt, use these methods.
  917.  
  918. =cut
  919.  
  920. #=head4 The data_sources method
  921. #=POD-Perl-5.6.x=begin
  922.  
  923. =pod
  924.  
  925. =back
  926.  
  927. =over 2
  928.  
  929. =item The data_sources method
  930.  
  931. =cut
  932.  
  933. #=POD-Perl-5.6.x=end
  934.  
  935. =pod
  936.  
  937. The data_sources method must populate and return a list of valid data
  938. sources, prefixed with the "dbi:Driver" incantation that allows them to
  939. be used in the first argument of the C<DBI-E<gt>connect> method.
  940. An example of this might be scanning the I<$HOME/.odbcini> file on Unix
  941. for ODBC data sources (DSNs).
  942. As a trivial example, consider a fixed list of data sources:
  943.  
  944.   sub data_sources
  945.   {
  946.       my($srh, $attr) = @_;
  947.       my(@list) = ();
  948.       # You need more sophisticated code than this to set @list...
  949.       push @list, "dbi:Driver:abc";
  950.       push @list, "dbi:Driver:def";
  951.       push @list, "dbi:Driver:ghi";
  952.       # End of code to set @list
  953.       return @list;
  954.   }
  955.  
  956. =cut
  957.  
  958. #=head4 Error handling
  959. #=POD-Perl-5.6.x=begin
  960.  
  961. =pod
  962.  
  963. =back
  964.  
  965. =over 2
  966.  
  967. =item Error handling
  968.  
  969. =cut
  970.  
  971. #=POD-Perl-5.6.x=end
  972.  
  973. =pod
  974.  
  975. It is quite likely that something fails in the connect method.
  976. With DBD::File for example, you might catch an error when setting the
  977. current directory to something not existent by using the
  978. (driver-specific) f_dir attribute.
  979.  
  980. To report an error, you use the C<DBI::set_err> method:
  981.  
  982.   $h->DBI::set_err($errcode, $errmsg);
  983.  
  984. This will ensure that the error is recorded correctly and that
  985. RaiseError and PrintError etc are handled correctly.
  986. Typically you'll
  987. always use the method instance, aka your method's first argument.
  988.  
  989. As set_err always returns undef your error handling code can
  990. usually be simplified to something like this:
  991.  
  992.   return $h->DBI::set_err($errcode, $errmsg) if ...;
  993.  
  994. =cut
  995.  
  996. #=head4 The disconnect_all method
  997. #=POD-Perl-5.6.x=begin
  998.  
  999. =pod
  1000.  
  1001. =back
  1002.  
  1003. =over 2
  1004.  
  1005. =item The disconnect_all method
  1006.  
  1007. =cut
  1008.  
  1009. #=POD-Perl-5.6.x=end
  1010.  
  1011. =pod
  1012.  
  1013. If you need to release any resources when the driver is unloaded, you
  1014. can provide a disconnect_all method.
  1015.  
  1016. =cut
  1017.  
  1018. #=head4 Other driver handle methods
  1019. #=POD-Perl-5.6.x=begin
  1020.  
  1021. =pod
  1022.  
  1023. =back
  1024.  
  1025. =over 2
  1026.  
  1027. =item Other driver handle methods
  1028.  
  1029. =cut
  1030.  
  1031. #=POD-Perl-5.6.x=end
  1032.  
  1033. =pod
  1034.  
  1035. If you need any other driver handle methods, they can follow here.
  1036.  
  1037. =cut
  1038.  
  1039. #=head3 The DBD::Driver::db package
  1040. #=POD-Perl-5.6.x=begin
  1041.  
  1042. =pod
  1043.  
  1044. =back
  1045.  
  1046. =over 2
  1047.  
  1048. =item The DBD::Driver::db package
  1049.  
  1050. =cut
  1051.  
  1052. #=POD-Perl-5.6.x=end
  1053.  
  1054. =pod
  1055.  
  1056. =cut
  1057.  
  1058. #=head4 The statement handle constructor
  1059. #=POD-Perl-5.6.x=begin
  1060.  
  1061. =pod
  1062.  
  1063. =back
  1064.  
  1065. =over 2
  1066.  
  1067. =item The statement handle constructor
  1068.  
  1069. =cut
  1070.  
  1071. #=POD-Perl-5.6.x=end
  1072.  
  1073. =pod
  1074.  
  1075. There's nothing much new in the statement handle constructor.
  1076.  
  1077.   package DBD::Driver::db; # ====== DATABASE ======
  1078.  
  1079.   $DBD::Driver::db::imp_data_size = 0;
  1080.  
  1081.   sub prepare
  1082.   {
  1083.       my ($dbh, $statement, @attribs) = @_;
  1084.  
  1085.       # create a 'blank' sth
  1086.       my $sth = DBI::_new_sth($dbh, {
  1087.           'Statement' => $statement,
  1088.           });
  1089.  
  1090.       # Setup module specific data
  1091.       $sth->STORE('drv_params', []);
  1092.       $sth->STORE('NUM_OF_PARAMS', ($statement =~ tr/?//));
  1093.  
  1094.       $sth;
  1095.   }
  1096.  
  1097. This is still the same: check the arguments and call the super class
  1098. constructor I<DBI::_new_sth>.
  1099. The C<Statement> attribute should be cached as shown.
  1100. Note the prefix I<drv_> in the attribute names: it is required that
  1101. your private attributes are lowercased and use such a prefix.
  1102.  
  1103. Note that we parse the statement here in order to set the attribute
  1104. I<NUM_OF_PARAMS>.
  1105. The technique illustrated is not very reliable; it can be confused by
  1106. question marks appearing in quoted strings, delimited identifiers or in
  1107. SQL comments that are part of the SQL statement.
  1108. We could set I<NUM_OF_PARAMS> in the I<execute> method instead because
  1109. the DBI specification explicitly allows a driver to defer this, but then
  1110. the user could not call I<bind_param>.
  1111.  
  1112. =cut
  1113.  
  1114. #=head4 Transaction handling
  1115. #=POD-Perl-5.6.x=begin
  1116.  
  1117. =pod
  1118.  
  1119. =back
  1120.  
  1121. =over 2
  1122.  
  1123. =item Transaction handling
  1124.  
  1125. =cut
  1126.  
  1127. #=POD-Perl-5.6.x=end
  1128.  
  1129. =pod
  1130.  
  1131. Pure Perl drivers will rarely support transactions. Thus your I<commit>
  1132. and I<rollback> methods will typically be quite simple:
  1133.  
  1134.   sub commit
  1135.   {
  1136.       my ($dbh) = @_;
  1137.       if ($dbh->FETCH('Warn')) {
  1138.           warn("Commit ineffective while AutoCommit is on");
  1139.       }
  1140.       0;
  1141.   }
  1142.  
  1143.   sub rollback {
  1144.       my ($dbh) = @_;
  1145.       if ($dbh->FETCH('Warn')) {
  1146.           warn("Rollback ineffective while AutoCommit is on");
  1147.       }
  1148.       0;
  1149.   }
  1150.  
  1151. Or even simpler, just use the default methods provided by the DBI that
  1152. do nothing except return undef.
  1153.  
  1154. The DBI's default begin_work method can be used by inheritance.
  1155.  
  1156. =cut
  1157.  
  1158. #=head4 The STORE and FETCH methods
  1159. #=POD-Perl-5.6.x=begin
  1160.  
  1161. =pod
  1162.  
  1163. =back
  1164.  
  1165. =over 2
  1166.  
  1167. =item The STORE and FETCH methods
  1168.  
  1169. =cut
  1170.  
  1171. #=POD-Perl-5.6.x=end
  1172.  
  1173. =pod
  1174.  
  1175. These methods (that we have already used, see above) are called for
  1176. you, whenever the user does a:
  1177.  
  1178.   $dbh->{$attr} = $val;
  1179.  
  1180. or, respectively,
  1181.  
  1182.   $val = $dbh->{$attr};
  1183.  
  1184. See L<perltie(1)> for details on tied hash refs to understand why these
  1185. methods are required.
  1186.  
  1187. The DBI will handle most attributes for you, in particular attributes
  1188. like I<RaiseError> or I<PrintError>.
  1189. All you have to do is handle your driver's private attributes and any
  1190. attributes, like AutoCommit and ChopBlanks, that the DBI can't handle
  1191. for you.
  1192. A good example might look like this:
  1193.  
  1194.   sub STORE
  1195.   {
  1196.       my ($dbh, $attr, $val) = @_;
  1197.       if ($attr eq 'AutoCommit') {
  1198.           # AutoCommit is currently the only standard attribute we have
  1199.           # to consider.
  1200.           if (!$val) { die "Can't disable AutoCommit"; }
  1201.           return 1;
  1202.       }
  1203.       if ($attr =~ m/^drv_/) {
  1204.           # Handle only our private attributes here
  1205.           # Note that we could trigger arbitrary actions.
  1206.           # Ideally we should catch unknown attributes.
  1207.           $dbh->{$attr} = $val; # Yes, we are allowed to do this,
  1208.           return 1;             # but only for our private attributes
  1209.       }
  1210.       # Else pass up to DBI to handle for us
  1211.       $dbh->SUPER::STORE($attr, $val);
  1212.   }
  1213.  
  1214.   sub FETCH
  1215.   {
  1216.       my ($dbh, $attr) = @_;
  1217.       if ($attr eq 'AutoCommit') { return 1; }
  1218.       if ($attr =~ m/^drv_/) {
  1219.           # Handle only our private attributes here
  1220.           # Note that we could trigger arbitrary actions.
  1221.           return $dbh->{$attr}; # Yes, we are allowed to do this,
  1222.                                 # but only for our private attributes
  1223.       }
  1224.       # Else pass up to DBI to handle
  1225.       $dbh->SUPER::FETCH($attr);
  1226.   }
  1227.  
  1228. The DBI will actually store and fetch driver-specific attributes (with all
  1229. lowercase names) without warning or error, so there's actually no need to
  1230. implement driver-specific any code in your FETCH and STORE methods unless
  1231. you need extra logic/checks, beyond getting or setting the value.
  1232.  
  1233. Unless your driver documentation indicates otherwise, the return value of
  1234. the STORE method is unspecified and the caller shouldn't use that value.
  1235.  
  1236. =cut
  1237.  
  1238. #=head4 Other database handle methods
  1239. #=POD-Perl-5.6.x=begin
  1240.  
  1241. =pod
  1242.  
  1243. =back
  1244.  
  1245. =over 2
  1246.  
  1247. =item Other database handle methods
  1248.  
  1249. =cut
  1250.  
  1251. #=POD-Perl-5.6.x=end
  1252.  
  1253. =pod
  1254.  
  1255. As with the driver package, other database handle methods may follow
  1256. here.
  1257. In particular you should consider a (possibly empty) I<disconnect>
  1258. method and possibly a I<quote> method if DBI's default isn't correct for
  1259. you.
  1260.  
  1261. =cut
  1262.  
  1263. #=head3 The DBD::Driver::st package
  1264. #=POD-Perl-5.6.x=begin
  1265.  
  1266. =pod
  1267.  
  1268. =back
  1269.  
  1270. =over 2
  1271.  
  1272. =item The DBD::Driver::st package
  1273.  
  1274. =cut
  1275.  
  1276. #=POD-Perl-5.6.x=end
  1277.  
  1278. =pod
  1279.  
  1280. =cut
  1281.  
  1282. #=head4 The execute method
  1283. #=POD-Perl-5.6.x=begin
  1284.  
  1285. =pod
  1286.  
  1287. =back
  1288.  
  1289. =over 2
  1290.  
  1291. =item The execute method
  1292.  
  1293. =cut
  1294.  
  1295. #=POD-Perl-5.6.x=end
  1296.  
  1297. =pod
  1298.  
  1299. This is perhaps the most difficult method because we have to consider
  1300. parameter bindings here. We present a simplified implementation by
  1301. using the I<drv_params> attribute from above:
  1302.  
  1303.   package DBD::Driver::st;
  1304.  
  1305.   $DBD::Driver::st::imp_data_size = 0;
  1306.  
  1307.   sub bind_param
  1308.   {
  1309.       my ($sth, $pNum, $val, $attr) = @_;
  1310.       my $type = (ref $attr) ? $attr->{TYPE} : $attr;
  1311.       if ($type) {
  1312.           my $dbh = $sth->{Database};
  1313.           $val = $dbh->quote($sth, $type);
  1314.       }
  1315.       my $params = $sth->FETCH('drv_params');
  1316.       $params->[$pNum-1] = $val;
  1317.       1;
  1318.   }
  1319.  
  1320.   sub execute
  1321.   {
  1322.       my ($sth, @bind_values) = @_;
  1323.  
  1324.       # start of by finishing any previous execution if still active
  1325.       $sth->finish if $sth->{Active};
  1326.  
  1327.       my $params = (@bind_values) ?
  1328.           \@bind_values : $sth->FETCH('drv_params');
  1329.       my $numParam = $sth->FETCH('NUM_OF_PARAMS');
  1330.       return $sth->set_err(1, "Wrong number of parameters")
  1331.           if @$params != $numParam;
  1332.       my $statement = $sth->{'Statement'};
  1333.       for (my $i = 0;  $i < $numParam;  $i++) {
  1334.           $statement =~ s/?/$params->[$i]/; # XXX doesn't deal with quoting etc!
  1335.       }
  1336.       # Do anything ... we assume that an array ref of rows is
  1337.       # created and store it:
  1338.       $sth->{'drv_data'} = $data;
  1339.       $sth->{'drv_rows'} = @$data; # number of rows
  1340.       $sth->STORE('NUM_OF_FIELDS') = $numFields;
  1341.       @$data || '0E0';
  1342.   }
  1343.  
  1344. There are a number of things you should note here.
  1345. We setup the NUM_OF_FIELDS attribute
  1346. here, because this is essential for I<bind_columns> to work.
  1347. We use attribute I<$sth->{'Statement'}> which we created
  1348. within I<prepare>. The attribute I<$sth->{'Database'}>, which is
  1349. nothing else than the I<dbh>, was automatically created by DBI.
  1350.  
  1351. Finally note that (as specified in the DBI specification) we return the
  1352. string '0E0' instead of the number 0, so that the result tests true but
  1353. equal to zero.
  1354.  
  1355.   $sth->execute() or die $sth->errstr;
  1356.  
  1357. =cut
  1358.  
  1359. #=head4 Fetching data
  1360. #=POD-Perl-5.6.x=begin
  1361.  
  1362. =pod
  1363.  
  1364. =back
  1365.  
  1366. =over 2
  1367.  
  1368. =item Fetching data
  1369.  
  1370. =cut
  1371.  
  1372. #=POD-Perl-5.6.x=end
  1373.  
  1374. =pod
  1375.  
  1376. We should not implement the methods I<fetchrow_array>, I<fetchall_arrayref>,
  1377. ... because these are already part of DBI.
  1378. All we need is the method
  1379. I<fetchrow_arrayref>:
  1380.  
  1381.   sub fetchrow_arrayref
  1382.   {
  1383.       my ($sth) = @_;
  1384.       my $data = $sth->FETCH('drv_data');
  1385.       my $row = shift @$data;
  1386.       if (!$row) {
  1387.           $sth->{Active} = 0; # mark as no longer active 
  1388.           return undef;
  1389.       }
  1390.       if ($sth->FETCH('ChopBlanks')) {
  1391.           map { $_ =~ s/\s+$//; } @$row;
  1392.       }
  1393.       return $sth->_set_fbav($row);
  1394.   }
  1395.   *fetch = \&fetchrow_arrayref; # required alias for fetchrow_arrayref
  1396.  
  1397.   sub rows { shift->FETCH('drv_rows') }
  1398.  
  1399. Note the use of the method I<_set_fbav>: This is required so that
  1400. I<bind_col> and I<bind_columns> work.
  1401.  
  1402. =cut
  1403.  
  1404. #=head4 Statement attributes
  1405. #=POD-Perl-5.6.x=begin
  1406.  
  1407. =pod
  1408.  
  1409. =back
  1410.  
  1411. =over 2
  1412.  
  1413. =item Statement attributes
  1414.  
  1415. =cut
  1416.  
  1417. #=POD-Perl-5.6.x=end
  1418.  
  1419. =pod
  1420.  
  1421. The main difference between dbh and sth attributes is, that you
  1422. should implement a lot of attributes here that are required by
  1423. the DBI, such as I<NAME>, I<NULLABLE>, I<TYPE>, ...
  1424.  
  1425. Besides that the STORE and FETCH methods are mainly the same
  1426. as above for dbh's.
  1427.  
  1428. =cut
  1429.  
  1430. #=head4 Other statement methods
  1431. #=POD-Perl-5.6.x=begin
  1432.  
  1433. =pod
  1434.  
  1435. =back
  1436.  
  1437. =over 2
  1438.  
  1439. =item Other statement methods
  1440.  
  1441. =cut
  1442.  
  1443. #=POD-Perl-5.6.x=end
  1444.  
  1445. =pod
  1446.  
  1447. A trivial C<finish> method to discard the stored data and do
  1448. $sth->SUPER::finish;
  1449.  
  1450. A C<table_info> method to return details of available tables.
  1451.  
  1452. A C<type_info_all> method to return details of supported types.
  1453.  
  1454. And perhaps some other methods that are not part of the DBI
  1455. specification, in particular to make metadata available.
  1456. Considering Tim's recent postings, do yourself a favour and follow the
  1457. ODBC driver.
  1458.  
  1459. =cut
  1460.  
  1461. #=POD-Perl-5.6.x=begin
  1462.  
  1463. =pod
  1464.  
  1465. =back
  1466.  
  1467. =cut
  1468.  
  1469. #=POD-Perl-5.6.x=end
  1470.  
  1471. =pod
  1472.  
  1473. =head2 Tests
  1474.  
  1475. The test process should conform as closely as possibly to the Perl
  1476. standard test harness.
  1477.  
  1478. In particular, most (all) of the tests should be run in the t sub-directory,
  1479. and should simply produce an 'ok' when run under 'make test'.
  1480. For details on how this is done, see the Camel book and the section in
  1481. Chapter 7, "The Standard Perl Library" on L<Test::Harness>.
  1482.  
  1483. The tests may need to adapt to the type of database which is being
  1484. used for testing, and to the privileges of the user testing the
  1485. driver.
  1486.  
  1487. The DBD::Informix test code has to adapt in a number of places to the
  1488. type of database to which it is connected as different Informix
  1489. databases have different capabilities.
  1490. For example, some of the tests are for databases without transaction
  1491. logs; others are for databases with a transaction log.
  1492. Some versions of the server have support for blobs, or stored
  1493. procedures, or user-defined data types, and others do not.
  1494. When a complete file of tests must be skipped, you can provide a reason
  1495. in a pseudo-comment:
  1496.  
  1497.     if ($no_transactions_available)
  1498.     {
  1499.         print "1..0 # Skip: No transactions available\n";
  1500.         exit 0;
  1501.     }
  1502.  
  1503. Consider downloading the DBD::Informix code and look at the code in
  1504. DBD/Informix/TestHarness.pm which is used throughout the
  1505. DBD::Informix tests in the t sub-directory.
  1506.  
  1507. =head1 CREATING A C/XS DRIVER
  1508.  
  1509. Creating a new C/XS driver from scratch will always be a daunting task.
  1510. You can and should greatly simplify your task by taking a good
  1511. reference driver implementation and modifying that to match the
  1512. database product for which you are writing a driver.
  1513.  
  1514. The de facto reference driver has been the one for DBD::Oracle written
  1515. by Tim Bunce, who is also the author of the DBI package. The DBD::Oracle
  1516. module is a good example of a driver implemented around a C-level API.
  1517.  
  1518. Nowadays it it seems better to base on DBD::ODBC, another driver
  1519. maintained by Tim and Jeff Urlwin, because it offers a lot of metadata
  1520. and seems to become the guideline for the future development. (Also as
  1521. DBD::Oracle digs deeper into the Oracle 8 OCI interface it'll get even
  1522. more hairy than it is now.)
  1523.  
  1524. The DBD::Informix driver is one driver implemented using embedded SQL
  1525. instead of a function-based API.
  1526. DBD::Ingres may also be worth a look.
  1527.  
  1528. =head2 C/XS version of Driver.pm
  1529.  
  1530. A lot of the code in the Driver.pm file is very similar to the code for pure Perl modules
  1531. - see above.  However,
  1532. there are also some subtle (and not so subtle) differences, including:
  1533.  
  1534. =over 8
  1535.  
  1536. =item *
  1537.  
  1538. The variables $DBD::File::{dr|db|st}::imp_data_size are not defined
  1539. here, but in the XS code, because they declare the size of certain
  1540. C structures.
  1541.  
  1542. =item *
  1543.  
  1544. Some methods are typically moved to the XS code, in particular
  1545. I<prepare>, I<execute>, I<disconnect>, I<disconnect_all> and the STORE
  1546. and FETCH methods.
  1547.  
  1548. =item *
  1549.  
  1550. Other methods are still part of C<Driver.pm>, but have callbacks to
  1551. the XS code.
  1552.  
  1553. =item *
  1554.  
  1555. If the driver-specific parts of the imp_drh_t structure need to be
  1556. formally initialized (which does not seem to be a common requirement),
  1557. then you need to add a call to an appropriate XS function in the driver
  1558. method of DBD::Driver::driver, and you define the corresponding function
  1559. in Driver.xs, and you define the C code in dbdimp.c and the prototype in
  1560. dbdimp.h.
  1561.  
  1562. For example, DBD::Informix has such a requirement, and adds the
  1563. following call after the call to _new_drh in Informix.pm:
  1564.  
  1565.   DBD::Informix::dr::driver_init($drh);
  1566.  
  1567. and the following code in Informix.xs:
  1568.  
  1569.   # Initialize the DBD::Informix driver data structure
  1570.   void
  1571.   driver_init(drh)
  1572.       SV *drh
  1573.       CODE:
  1574.       ST(0) = dbd_ix_dr_driver_init(drh) ? &sv_yes : &sv_no;
  1575.  
  1576. and the code in dbdimp.h declares:
  1577.  
  1578.   extern int dbd_ix_dr_driver_init(SV *drh);
  1579.  
  1580. and the code in dbdimp.ec (equivalent to dbdimp.c) defines:
  1581.  
  1582.   /* Formally initialize the DBD::Informix driver structure */
  1583.   int
  1584.   dbd_ix_dr_driver(SV *drh)
  1585.   {
  1586.       D_imp_drh(drh);
  1587.       imp_drh->n_connections = 0;       /* No active connections */
  1588.       imp_drh->current_connection = 0;  /* No current connection */
  1589.       imp_drh->multipleconnections = (ESQLC_VERSION >= 600) ? True : False;
  1590.       dbd_ix_link_newhead(&imp_drh->head);  /* Empty linked list of connections */
  1591.       return 1;
  1592.   }
  1593.  
  1594. DBD::Oracle has a similar requirement but gets around it by checking
  1595. whether the private data part of the driver handle is all zeroed out,
  1596. rather than add extra functions.
  1597.  
  1598. =back
  1599.  
  1600. Now let's take a closer look at an excerpt from Oracle.pm (revised
  1601. heavily to remove idiosyncrasies) as an example.
  1602. We also ignore things that are already discussed for pure Perl drivers.
  1603.  
  1604. =cut
  1605.  
  1606. #=head3 The connect method
  1607. #=POD-Perl-5.6.x=begin
  1608.  
  1609. =pod
  1610.  
  1611. =over 2
  1612.  
  1613. =item The connect method
  1614.  
  1615. =cut
  1616.  
  1617. #=POD-Perl-5.6.x=end
  1618.  
  1619. =pod
  1620.  
  1621. The connect method is the database handle constructor.
  1622. You could write either of two versions of this method: either one which
  1623. takes connection attributes (new code) and one which ignores them (old
  1624. code only).
  1625. If you ignore the connection attributes, then you omit all mention of
  1626. the $auth variable (which is a reference to a hash of attributes), and
  1627. the XS system manages the differences for you.
  1628.  
  1629.   sub connect
  1630.   {
  1631.       my ($drh, $dbname, $user, $auth, $attr) = @_;
  1632.  
  1633.       # Some database specific verifications, default settings
  1634.       # and the like following here. This should only include
  1635.       # syntax checks or similar stuff where it's legal to
  1636.       # 'die' in case of errors.
  1637.  
  1638.       my $dbh = DBI::_new_dbh($drh, {
  1639.               'Name'   => $dbname,
  1640.           })
  1641.           or return undef;
  1642.  
  1643.       # Call the driver-specific function _login in Driver.xs file which
  1644.       # calls the DBMS-specific function(s) to connect to the database,
  1645.       # and populate internal handle data.
  1646.       DBD::Driver::db::_login($dbh, $dbname, $user, $auth, $attr)
  1647.           or return undef;
  1648.  
  1649.       $dbh;
  1650.   }
  1651.  
  1652. This is mostly the same as in the pure Perl case, the exception being
  1653. the use of the private I<_login> callback, which is the function that
  1654. will really connect to the database.
  1655. It is implemented in Driver.xst (you should not implement it) and calls
  1656. I<dbd_db_login6> from I<dbdimp.c>.
  1657. See below for details.
  1658.  
  1659. =over 4
  1660.  
  1661. *FIX ME* Discuss removing attributes from hash reference as an optimization
  1662. to skip later calls to $dbh->STORE made by DBI->connect.
  1663.  
  1664. *FIX ME* Discuss removing attributes in Perl code.
  1665.  
  1666. *FIX ME* Discuss removing attributes in C code.
  1667.  
  1668. =back
  1669.  
  1670. =cut
  1671.  
  1672. #=head3 The disconnect_all method
  1673. #=POD-Perl-5.6.x=begin
  1674.  
  1675. =pod
  1676.  
  1677. =back
  1678.  
  1679. =over 2
  1680.  
  1681. =item The disconnect_all method
  1682.  
  1683. =cut
  1684.  
  1685. #=POD-Perl-5.6.x=end
  1686.  
  1687. =pod
  1688.  
  1689. *FIX ME* T.B.S
  1690.  
  1691. =cut
  1692.  
  1693. #=head3 The data_sources method
  1694. #=POD-Perl-5.6.x=begin
  1695.  
  1696. =pod
  1697.  
  1698. =back
  1699.  
  1700. =over 2
  1701.  
  1702. =item The data_sources method
  1703.  
  1704. =cut
  1705.  
  1706. #=POD-Perl-5.6.x=end
  1707.  
  1708. =pod
  1709.  
  1710. If your I<data_sources> method can be implemented in pure Perl, then do
  1711. so because it is easier than doing it in XS code (see the section above
  1712. for pure Perl drivers).
  1713. If your I<data_sources> method must call onto compiled functions, then
  1714. you will need to define dbd_dr_data_sources in your dbdimp.h file, which
  1715. will trigger Driver.xst (in DBI v1.33 or greater) to generate the XS
  1716. code that calls your actual C function (see the discussion below for
  1717. details) and you do not code anything in Driver.pm to handle it.
  1718.  
  1719. =cut
  1720.  
  1721. #=head3 The prepare method
  1722. #=POD-Perl-5.6.x=begin
  1723.  
  1724. =pod
  1725.  
  1726. =back
  1727.  
  1728. =over 2
  1729.  
  1730. =item The prepare method
  1731.  
  1732. =cut
  1733.  
  1734. #=POD-Perl-5.6.x=end
  1735.  
  1736. =pod
  1737.  
  1738. The prepare method is the statement handle constructor, and most of it
  1739. is not new.
  1740. Like the I<connect> method, it now has a C callback:
  1741.  
  1742.   package DBD::Driver::db; # ====== DATABASE ======
  1743.   use strict;
  1744.  
  1745.   sub prepare
  1746.   {
  1747.       my ($dbh, $statement, $attribs) = @_;
  1748.  
  1749.       # create a 'blank' sth
  1750.       my $sth = DBI::_new_sth($dbh, {
  1751.           'Statement' => $statement,
  1752.           })
  1753.           or return undef;
  1754.  
  1755.       # Call the driver-specific function _prepare in Driver.xs file
  1756.       # which calls the DBMS-specific function(s) to prepare a statement
  1757.       # and populate internal handle data.
  1758.       DBD::Driver::st::_prepare($sth, $statement, $attribs)
  1759.           or return undef;
  1760.       $sth;
  1761.   }
  1762.  
  1763. =cut
  1764.  
  1765. #=head3 The execute method
  1766. #=POD-Perl-5.6.x=begin
  1767.  
  1768. =pod
  1769.  
  1770. =back
  1771.  
  1772. =over 2
  1773.  
  1774. =item The execute method
  1775.  
  1776. =cut
  1777.  
  1778. #=POD-Perl-5.6.x=end
  1779.  
  1780. =pod
  1781.  
  1782. *FIX ME* T.B.S
  1783.  
  1784. =cut
  1785.  
  1786. #=head3 The fetchrow_arrayref method
  1787. #=POD-Perl-5.6.x=begin
  1788.  
  1789. =pod
  1790.  
  1791. =back
  1792.  
  1793. =over 2
  1794.  
  1795. =item The fetchrow_arrayref method
  1796.  
  1797. =cut
  1798.  
  1799. #=POD-Perl-5.6.x=end
  1800.  
  1801. =pod
  1802.  
  1803. *FIX ME* T.B.S
  1804.  
  1805. =cut
  1806.  
  1807. #=head3 Other methods?
  1808. #=POD-Perl-5.6.x=begin
  1809.  
  1810. =pod
  1811.  
  1812. =back
  1813.  
  1814. =over 2
  1815.  
  1816. =item Other methods?
  1817.  
  1818. =cut
  1819.  
  1820. #=POD-Perl-5.6.x=end
  1821.  
  1822. =pod
  1823.  
  1824. *FIX ME* T.B.S
  1825.  
  1826. =cut
  1827.  
  1828. #=POD-Perl-5.6.x=begin
  1829.  
  1830. =pod
  1831.  
  1832. =back
  1833.  
  1834. =cut
  1835.  
  1836. #=POD-Perl-5.6.x=end
  1837.  
  1838. =pod
  1839.  
  1840. =head2 Driver.xs
  1841.  
  1842. Driver.xs should look something like this:
  1843.  
  1844.   #include "Driver.h"
  1845.  
  1846.   DBISTATE_DECLARE;
  1847.  
  1848.   INCLUDE: Driver.xsi
  1849.  
  1850.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::dr
  1851.  
  1852.   /* Non-standard drh XS methods following here, if any.       */
  1853.   /* If none (the usual case), omit the MODULE line above too. */
  1854.  
  1855.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::db
  1856.  
  1857.   /* Non-standard dbh XS methods following here, if any.       */
  1858.   /* Currently this includes things like _list_tables from     */
  1859.   /* DBD::mSQL and DBD::mysql.                                 */
  1860.  
  1861.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::st
  1862.  
  1863.   /* Non-standard sth XS methods following here, if any.       */
  1864.   /* In particular this includes things like _list_fields from */
  1865.   /* DBD::mSQL and DBD::mysql for accessing metadata.          */
  1866.  
  1867. Note especially the include of I<Driver.xsi> here: DBI inserts stub
  1868. functions for almost all private methods here which will typically do
  1869. much work for you.
  1870. Wherever you really have to implement something, it will call a private
  1871. function in I<dbdimp.c>, and this is what you have to implement.
  1872.  
  1873. You need to set up an extra routine if your driver needs to export
  1874. constants of its own, analogous to the SQL types available when you say:
  1875.  
  1876.   use DBI qw(:sql_types);
  1877.  
  1878. *FIX ME* T.B.S
  1879.  
  1880. =head2 Driver.h
  1881.  
  1882. Driver.h is very simple and the operational contents should look like this:
  1883.  
  1884.   #ifndef DRIVER_H_INCLUDED
  1885.   #define DRIVER_H_INCLUDED
  1886.  
  1887.   #define NEED_DBIXS_VERSION 93    /* 93 for DBI versions 1.00 to 1.32 */
  1888.  
  1889.   #include <DBIXS.h>      /* installed by the DBI module  */
  1890.  
  1891.   #include "dbdimp.h"
  1892.  
  1893.   #include <dbd_xsh.h>    /* installed by the DBI module  */
  1894.  
  1895.   #endif /* DRIVER_H_INCLUDED */
  1896.  
  1897. The C<DBIXS.h> header defines most of the interesting information that
  1898. the writer of a driver needs.
  1899. The file C<dbd_xsh.h> header provides prototype declarations for the C
  1900. functions that you might decide to implement.
  1901. Note that you should normally only define one of I<dbd_db_login> and
  1902. I<dbd_db_login6> unless you are intent on supporting really old versions of
  1903. DBI (prior to DBI 1.06) as well as modern versions.
  1904. The only standard, DBI-mandated functions that you need write are those
  1905. specified in the dbd_xsh.h header.
  1906. You might also add extra driver-specific functions in Driver.xs.
  1907.  
  1908. =head2 Implementation header dbdimp.h
  1909.  
  1910. This header file has two jobs:
  1911.  
  1912. First it defines data structures for your private part of the handles.
  1913.  
  1914. Second it defines macros that rename the generic names like
  1915. I<dbd_db_login> to database specific names like I<ora_db_login>. This
  1916. avoids name clashes and enables use of different drivers when you work
  1917. with a statically linked perl.
  1918.  
  1919. It also will have the important task of disabling XS methods that you
  1920. don't want to implement.
  1921.  
  1922. Finally, the macros will also be used to select alternate
  1923. implementations of some functions.
  1924. For example, the I<dbd_db_login> function is not passed the attribute
  1925. hash.
  1926. Since DBI v1.06, if a I<dbd_db_login6> macro is defined (for a function
  1927. with 6 arguments), it will be used instead with the attribute hash
  1928. passed as the sixth argument.
  1929.  
  1930. People used to just pick Oracle's dbdimp.c and use the same names,
  1931. structures and types.
  1932. I strongly recommend against that.
  1933. At first glance this saves time, but your implementation will be less
  1934. readable.
  1935. It was just hell when I had to separate DBI specific parts, Oracle
  1936. specific parts, mSQL specific parts and mysql specific parts in
  1937. DBD::mysql's I<dbdimp.h> and I<dbdimp.c>.
  1938. (DBD::mysql was a port of DBD::mSQL which was based on DBD::Oracle.)
  1939. [Seconded, based on the experience taking DBD::Informix apart, even
  1940. though the version inherited in 1996 was only based on DBD::Oracle.]
  1941.  
  1942. This part of the driver is I<your exclusive part>.
  1943. Rewrite it from scratch, so it will be clean and short: in other words,
  1944. a better piece of code.
  1945. (Of course keep an eye on other people's work.)
  1946.  
  1947.   struct imp_drh_st {
  1948.       dbih_drc_t com;           /* MUST be first element in structure   */
  1949.       /* Insert your driver handle attributes here */
  1950.   };
  1951.  
  1952.   struct imp_dbh_st {
  1953.       dbih_dbc_t com;           /* MUST be first element in structure   */
  1954.       /* Insert your database handle attributes here */
  1955.   };
  1956.  
  1957.   struct imp_sth_st {
  1958.       dbih_stc_t com;           /* MUST be first element in structure   */
  1959.       /* Insert your statement handle attributes here */
  1960.   };
  1961.  
  1962.   /*  Rename functions for avoiding name clashes; prototypes are  */
  1963.   /*  in dbd_xst.h                                                */
  1964.   #define dbd_init         drv_dr_init
  1965.   #define dbd_db_login6    drv_db_login
  1966.   #define dbd_db_do        drv_db_do
  1967.   ... many more here ...
  1968.  
  1969. These structures implement your private part of the handles.
  1970. You I<have> to use the name I<imp_dbh_{dr|db|st}> and the first field
  1971. I<must> be of type I<dbih_drc_t|_dbc_t|_stc_t> and I<must> be called
  1972. C<com>.
  1973. You should never access these fields directly, except by using the
  1974. I<DBIc_xxx> macros below.
  1975.  
  1976. =head2 Implementation source dbdimp.c
  1977.  
  1978. Conventionally, I<dbdimp.c> is the main implementation file (but
  1979. DBD::Informix calls the file dbdimp.ec).
  1980. This section includes a short note on each function that is used in the
  1981. Driver.xsi template and thus B<has> to be implemented.
  1982.  
  1983. Of course, you will probably also need to implement other support
  1984. functions, which should usually be file static if the are placed in
  1985. I<dbdimp.c>.
  1986. If they are placed in other files, you need to list those files in
  1987. Makefile.PL (and MANIFEST) to handle them correctly.
  1988.  
  1989. It is wise to adhere to a namespace convention for your functions to
  1990. avoid conflicts.
  1991. For example, for a driver with prefix "drv", you might call externally
  1992. visible functions "dbd_drv_xxxx".
  1993. You should also avoid non-constant global variables as much as possible
  1994. to improve the support for threading.
  1995.  
  1996. Since Perl 5.6 requires support for function prototypes (ANSI or ISO or
  1997. Standard C), you should write your code using function prototypes too.
  1998. Although technically DBI still supports Perl 5.005_03, which did not
  1999. mandate prototype support from the C compiler, the only platform where
  2000. prototypes are a problem is on HP-UX with the bundled C compiler (which
  2001. is strictly K&R).
  2002. The solution for that is to get a copy of the GNU Compiler Collection
  2003. (GCC, aka the GNU C Compiler) for HP-UX.
  2004.  
  2005. It is possible to use either the unmapped names such as C<dbd_init> or
  2006. the mapped names such as C<dbd_ix_dr_init> in the C<dbdimp.c> file.
  2007. DBD::Informix uses the mapped names which makes it easier to identify
  2008. where to look for linkage problems at runtime (which will report errors
  2009. using the mapped names).
  2010. Most other drivers, and in particular DBD::Oracle, use the unmapped
  2011. names in the source code which makes it a little easier to compare code
  2012. between drivers and eases discussions on the dbi-dev mailing list.
  2013. The majority of the code fragments here will use the unmapped names.
  2014.  
  2015. Ultimately, you should provide implementations for most fo the functions
  2016. listed in the I<dbd_xsh.h> header.
  2017. The exceptions are optional functions (such as I<dbd_st_rows>) and those
  2018. functions with alternative signatures, such as I<dbd_db_login6> and
  2019. I<dbd_db_login>.
  2020. Then you should only implement one of the alternatives, and generally
  2021. the newer one of the alternatives.
  2022.  
  2023. =cut
  2024.  
  2025. #=head3 The dbd_init method
  2026. #=POD-Perl-5.6.x=begin
  2027.  
  2028. =pod
  2029.  
  2030. =over 2
  2031.  
  2032. =item The dbd_init method
  2033.  
  2034. =cut
  2035.  
  2036. #=POD-Perl-5.6.x=end
  2037.  
  2038. =pod
  2039.  
  2040.   #include "Driver.h"
  2041.  
  2042.   DBISTATE_DECLARE;
  2043.  
  2044.   void dbd_init(dbistate_t* dbistate)
  2045.   {
  2046.       DBISTATE_INIT;  /*  Initialize the DBI macros  */
  2047.   }
  2048.  
  2049. The C<dbd_init> function will be called when your driver is first
  2050. loaded; the bootstrap command in DBD::Driver::dr::driver triggers this,
  2051. and the call is generated in the BOOT section of Driver.xst.
  2052. These statements are needed to allow your driver to use the DBI macros.
  2053. They will include your private header file I<dbdimp.h> in turn.
  2054. Note that DBISTATE_INIT requires the name of the argument to I<dbd_init>
  2055. to be called I<dbistate>.
  2056.  
  2057. =cut
  2058.  
  2059. #=head3 The dbd_drv_error method
  2060. #=POD-Perl-5.6.x=begin
  2061.  
  2062. =pod
  2063.  
  2064. =back
  2065.  
  2066. =over 2
  2067.  
  2068. =item The dbd_drv_error method
  2069.  
  2070. =cut
  2071.  
  2072. #=POD-Perl-5.6.x=end
  2073.  
  2074. =pod
  2075.  
  2076. You need a function to record errors so DBI can access them properly.
  2077. You can call it whatever you like, but we'll call it C<dbd_drv_error>
  2078. here.
  2079. The argument list depends on your database software; different systems
  2080. provide different ways to get at error information.
  2081.  
  2082.   static void dbd_drv_error(SV *h, int rc, const char *what)
  2083.   {
  2084.  
  2085. Note that I<h> is a generic handle, may it be a driver handle, a
  2086. database or a statement handle.
  2087.  
  2088.       D_imp_xxh(h);
  2089.  
  2090. This macro will declare and initialize a variable I<imp_xxh> with
  2091. a pointer to your private handle pointer. You may cast this to
  2092. to I<imp_drh_t>, I<imp_dbh_t> or I<imp_sth_t>.
  2093.  
  2094.   SV *errstr = DBIc_ERRSTR(imp_xxh);
  2095.   sv_setiv(DBIc_ERR(imp_xxh), (IV)rc);  /* set err early        */
  2096.   sv_setpv(errstr, what);
  2097.  
  2098. If your database supports SQLSTATE, you should also set the SQLSTATE value; for example,
  2099. DBD::Informix includes the line:
  2100.  
  2101.   sv_setpv(DBIc_STATE(imp_xxh), SQLSTATE);
  2102.  
  2103. Note the use of the macros DBIc_ERRSTR and DBIc_ERR for accessing the
  2104. handles error string and error code.
  2105.  
  2106. The (obsolete) macros such as DBIh_EVENT2 should be removed from drivers.
  2107. The names I<dbis> and I<DBIS>, which were used in previous versions of this document,
  2108. should be replaced with the C<DBIc_STATE(imp_xxh)> macro.
  2109. The name DBILOGFP, which was also used in previous  versions of this document, should be
  2110. replaced by DBIc_LOGPIO(imp_xxh).
  2111. Your code should not call the C C<E<lt>stdio.hE<gt>> I/O functions; you should either use
  2112. C<PerlIO_printf>() as shown, or standard Perl functions such as C<warn>():
  2113.  
  2114.       if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
  2115.           PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s error %d recorded: %s\n",
  2116.               what, rc, SvPV(errstr,na));
  2117.  
  2118. Or:
  2119.  
  2120.       if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
  2121.           warn("%s error %d recorded: %s\n", what, rc, SvPV(errstr,na));
  2122.  
  2123. That's the first time we see how debug/trace logging works within a DBI
  2124. driver.  Make use of this as often as you can!
  2125.  
  2126. =cut
  2127.  
  2128. #=head3 The dbd_dr_data_sources method
  2129. #=POD-Perl-5.6.x=begin
  2130.  
  2131. =pod
  2132.  
  2133. =back
  2134.  
  2135. =over 2
  2136.  
  2137. =item The dbd_dr_data_sources method
  2138.  
  2139. =cut
  2140.  
  2141. #=POD-Perl-5.6.x=end
  2142.  
  2143. =pod
  2144.  
  2145. This method is optional; the support for it was added in DBI v1.33.
  2146.  
  2147. As noted in the discussion of Driver.pm, if the data sources can be
  2148. determined by pure Perl code, do it that way.
  2149. If, as in DBD::Informix, the information is obtained by a C function
  2150. call, then you need to define a function that matches the prototype:
  2151.  
  2152.   extern AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attrs);
  2153.  
  2154. An outline implementation for DBD::Informix follows, assuming that the
  2155. sqgetdbs() function call shown will return up to 100 databases names,
  2156. with the pointers to each name in the array dbsname and the name strings
  2157. themselves being stores in dbsarea.
  2158. The actual DBD::Informix implementation has a number of extra lines of
  2159. code, logs function entry and exit, reports the error from sqgetdbs(),
  2160. and uses #define'd constatnts for the array sizes.
  2161.  
  2162.   AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr)
  2163.   {
  2164.       int ndbs;
  2165.       int i;
  2166.       char *dbsname[100];
  2167.       char  dbsarea[10000];
  2168.       AV *av = Nullav;
  2169.  
  2170.       if (sqgetdbs(&ndbs, dbsname, 100, dbsarea, sizeof(dbsarea)) == 0)
  2171.       {
  2172.           av = NewAV();
  2173.           av_extend(av, (I32)ndbs);
  2174.           sv_2mortal((SV *)av);
  2175.           for (i = 0; i < ndbs; i++)
  2176.             av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i]));
  2177.       }
  2178.       return(av);
  2179.   }
  2180.  
  2181. =cut
  2182.  
  2183. #=head3 The dbd_db_login6 method
  2184. #=POD-Perl-5.6.x=begin
  2185.  
  2186. =pod
  2187.  
  2188. =back
  2189.  
  2190. =over 2
  2191.  
  2192. =item The dbd_db_login6 method
  2193.  
  2194. =cut
  2195.  
  2196. #=POD-Perl-5.6.x=end
  2197.  
  2198. =pod
  2199.  
  2200.   int dbd_db_login6(SV* dbh, imp_dbh_t* imp_dbh, char* dbname,
  2201.                    char* user, char* auth, SV *attr);
  2202.  
  2203. This function will really connect to the database.
  2204. The argument I<dbh> is the database handle.
  2205. I<imp_dbh> is the pointer to the handles private data, as is I<imp_xxx>
  2206. in I<dbd_drv_error> above.
  2207. The arguments I<dbname>, I<user>, I<auth> and I<attr> correspond to the
  2208. arguments of the driver handle's I<connect> method.
  2209.  
  2210. You will quite often use database specific attributes here, that are
  2211. specified in the DSN.
  2212. I recommend you parse the DSN (using Perl) within the I<connect> method
  2213. and pass the segments of the DSN via the attributes parameter through
  2214. I<_login> to I<dbd_db_login6>.
  2215. Here's how you fetch them; as an example we use I<hostname> attribute,
  2216. which can be up to 12 characters long excluding null terminator:
  2217.  
  2218.   SV** svp;
  2219.   STRLEN len;
  2220.   char* hostname;
  2221.  
  2222.   if ( (svp = DBD_ATTRIB_GET_SVP(attr, "drv_hostname", 12)) && SvTRUE(*svp)) {
  2223.       hostname = SvPV(*svp, len);
  2224.       DBD__ATTRIB_DELETE(attr, "drv_hostname", 12); /* avoid later STORE */
  2225.   } else {
  2226.       hostname = "localhost";
  2227.   }
  2228.  
  2229. Note that you can also obtain standard attributes such as AutoCommit and
  2230. ChopBlanks from the attributes parameter, using DBD_ATTRIB_GET_IV for
  2231. integer attributes.
  2232. If, for example, your database does not support transactions but
  2233. AutoCommit is set off (requesting transaction support), then you can
  2234. emulate a 'failure to connect'.
  2235.  
  2236. Now you should really connect to the database.
  2237. In general, if the connection fails, it is best to ensure that all
  2238. allocated resources are released so that the handle does not need to be
  2239. destroyed separately.
  2240. If you are successful (and possibly even if you fail but you have
  2241. allocated some resources), you should use the following macros:
  2242.  
  2243.   DBIc_IMPSET_on(imp_dbh);
  2244.  
  2245. This indicates that the driver (implementor) has allocated resources in
  2246. the imp_dbh structure and that the implementors private dbd_db_destroy
  2247. function should be called when the handle is destroyed.
  2248.  
  2249.   DBIc_ACTIVE_on(imp_dbh);
  2250.  
  2251. This indicates that the handle has an active connection to the server
  2252. and that the dbd_db_disconnect function should be called before the
  2253. handle is destroyed.
  2254.  
  2255. Note that if you do need to fail, you should report errors via the drh
  2256. or imp_drh rather than via dbh or imp_dbh because imp_dbh will be
  2257. destroyed by the failure, so errors recorded in that handle will not be
  2258. visible to DBI, and hence not the user either.
  2259. Note to that the function is passed dbh and imp_dbh, and there is a
  2260. macro D_imp_drh_from_dbh which can recover the imp_drh from the imp_dbh,
  2261. but there is no DBI macro to provide you with the drh given either the
  2262. imp_dbh or the dbh or the imp_drh (and there's no way to recover the dbh
  2263. given just the imp_dbh).
  2264. This suggests that despite the notes about dbd_drv_error above taking an
  2265. SV *, it may be better to have two error routines, one taking imp_dbh
  2266. and one taking imp_drh instead.
  2267. With care, you can factor most of the formatting code out so that these
  2268. are small routines calling onto a common error formatter.
  2269. See the code in DBD::Informix 1.05.00 for more information.
  2270.  
  2271. The I<dbd_db_login6> function should return TRUE for success, FALSE otherwise.
  2272.  
  2273. Drivers implemented long ago may define the five-argument function
  2274. I<dbd_db_login> instead of I<dbd_db_login6>.
  2275. The missing argument is the attributes.
  2276. There are ways to work around the missing attributes, but they are
  2277. ungainly; it is much better to use the 6-argument form.
  2278.  
  2279. =cut
  2280.  
  2281. #=head3 The dbd_db_commit and dbd_db_rollback methods
  2282. #=POD-Perl-5.6.x=begin
  2283.  
  2284. =pod
  2285.  
  2286. =back
  2287.  
  2288. =over 2
  2289.  
  2290. =item The dbd_db_commit and dbd_db_rollback methods
  2291.  
  2292. =cut
  2293.  
  2294. #=POD-Perl-5.6.x=end
  2295.  
  2296. =pod
  2297.  
  2298.   int dbd_db_commit(SV *dbh, imp_dbh_t *imp_dbh);
  2299.   int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh);
  2300.  
  2301. These are used for commit and rollback. They should return TRUE for
  2302. success, FALSE for error.
  2303.  
  2304. The arguments I<dbh> and I<imp_dbh> are the same as for I<dbd_db_login6>
  2305. above; I will omit describing them in what follows, as they appear
  2306. always.
  2307.  
  2308. These functions should return TRUE for success, FALSE otherwise.
  2309.  
  2310. =cut
  2311.  
  2312. #=head3 The dbd_db_disconnect method
  2313. #=POD-Perl-5.6.x=begin
  2314.  
  2315. =pod
  2316.  
  2317. =back
  2318.  
  2319. =over 2
  2320.  
  2321. =item The dbd_db_disconnect method
  2322.  
  2323. =cut
  2324.  
  2325. #=POD-Perl-5.6.x=end
  2326.  
  2327. =pod
  2328.  
  2329. This is your private part of the I<disconnect> method. Any dbh with
  2330. the I<ACTIVE> flag on must be disconnected. (Note that you have to set
  2331. it in I<dbd_db_connect> above.)
  2332.  
  2333.   int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh);
  2334.  
  2335. The database handle will return TRUE for success, FALSE otherwise.
  2336. In any case it should do a:
  2337.  
  2338.   DBIc_ACTIVE_off(imp_dbh);
  2339.  
  2340. before returning so DBI knows that I<dbd_db_disconnect> was executed.
  2341.  
  2342. Note that there's nothing to stop a dbh being I<disconnected> while it
  2343. still have active children.
  2344. If your database API reacts badly to trying to use an sth in this
  2345. situation then you'll need to add code like this to all sth methods:
  2346.  
  2347.   if (!DBIc_ACTIVE(DBIc_PARENT_COM(imp_sth)))
  2348.     return 0;
  2349.  
  2350. Alternatively, you can add code to your driver to keep explicit track of
  2351. the statement handles that exist for each database handle and arrange to
  2352. destroy those handles before disconnecting from the database.
  2353. There is code to do this in DBD::Informix.
  2354. Similar comments apply to the driver handle keeping track of all the
  2355. database handles.
  2356. Note that the code which destroys the subordinate handles should only
  2357. release the associated database resources and mark the handles inactive;
  2358. it does not attempt to free the actual handle structures.
  2359.  
  2360. This function should return TRUE for success, FALSE otherwise, but
  2361. it is not clear what anything can do about a failure.
  2362.  
  2363. =cut
  2364.  
  2365. #=head3 The dbd_db_discon_all method
  2366. #=POD-Perl-5.6.x=begin
  2367.  
  2368. =pod
  2369.  
  2370. =back
  2371.  
  2372. =over 2
  2373.  
  2374. =item The dbd_db_discon_all method
  2375.  
  2376. =cut
  2377.  
  2378. #=POD-Perl-5.6.x=end
  2379.  
  2380. =pod
  2381.  
  2382.   int dbd_discon_all (SV *drh, imp_drh_t *imp_drh);
  2383.  
  2384. This function may be called at shutdown time. It should make
  2385. best-efforts to disconnect all database handles - if possible. Some
  2386. databases don't support that, in which case you can do nothing
  2387. but return 'success'.
  2388.  
  2389. This function should return TRUE for success, FALSE otherwise, but
  2390. it is not clear what anything can do about a failure.
  2391.  
  2392. =cut
  2393.  
  2394. #=head3 The dbd_db_destroy method
  2395. #=POD-Perl-5.6.x=begin
  2396.  
  2397. =pod
  2398.  
  2399. =back
  2400.  
  2401. =over 2
  2402.  
  2403. =item The dbd_db_destroy method
  2404.  
  2405. =cut
  2406.  
  2407. #=POD-Perl-5.6.x=end
  2408.  
  2409. =pod
  2410.  
  2411. This is your private part of the database handle destructor. Any dbh with
  2412. the I<IMPSET> flag on must be destroyed, so that you can safely free
  2413. resources. (Note that you have to set it in I<dbd_db_connect> above.)
  2414.  
  2415.   void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh)
  2416.   {
  2417.       DBIc_IMPSET_off(imp_dbh);
  2418.   }
  2419.  
  2420. The DBI Driver.xst code will have called dbd_db_disconnect for you,
  2421. if the handle is still 'active', before calling dbd_db_destroy.
  2422.  
  2423. Before returning the function must switch IMPSET to off, so DBI knows
  2424. that the destructor was called.
  2425.  
  2426. A DBI handle doesn't keep references to its children. But children
  2427. do keep references to their parents. So a database handle won't be
  2428. DESTROY'd until all its children have been DESTROY'd.
  2429.  
  2430. =cut
  2431.  
  2432. #=head3 The dbd_db_STORE_attrib method
  2433. #=POD-Perl-5.6.x=begin
  2434.  
  2435. =pod
  2436.  
  2437. =back
  2438.  
  2439. =over 2
  2440.  
  2441. =item The dbd_db_STORE_attrib method
  2442.  
  2443. =cut
  2444.  
  2445. #=POD-Perl-5.6.x=end
  2446.  
  2447. =pod
  2448.  
  2449. This function handles
  2450.  
  2451.   $dbh->{$key} = $value;
  2452.  
  2453. Its prototype is:
  2454.  
  2455.   int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv,
  2456.                           SV* valuesv);
  2457.  
  2458. You do not handle all attributes; on the contrary, you should not handle
  2459. DBI attributes here: leave this to DBI.
  2460. (There are two exceptions, I<AutoCommit> and I<ChopBlanks>, which you
  2461. should care about.)
  2462.  
  2463. The return value is TRUE if you have handled the attribute or FALSE
  2464. otherwise. If you are handling an attribute and something fails, you
  2465. should call I<dbd_drv_error>, so DBI can raise exceptions, if desired.
  2466. If I<dbd_drv_error> returns, however, you have a problem: the user will
  2467. never know about the error, because he typically will not check
  2468. C<$dbh-E<gt>errstr>.
  2469.  
  2470. I cannot recommend a general way of going on, if I<dbd_drv_error> returns,
  2471. but there are examples where even the DBI specification expects that
  2472. you croak(). (See the I<AutoCommit> method in L<DBI(3)>.)
  2473.  
  2474. If you have to store attributes, you should either use your private
  2475. data structure imp_xxx, the handle hash (via (HV*)SvRV(dbh)), or use
  2476. the private imp_data.
  2477.  
  2478. The first is best for internal C values like integers or pointers and
  2479. where speed is important within the driver. The handle hash is best for
  2480. values the user may want to get/set via driver-specific attributes.
  2481. The private imp_data is an additional SV attached to the handle. You
  2482. could think of it as an unnamed handle attribute. It's not normally used.
  2483.  
  2484. =cut
  2485.  
  2486. #=head3 The dbd_db_FETCH_attrib method
  2487. #=POD-Perl-5.6.x=begin
  2488.  
  2489. =pod
  2490.  
  2491. =back
  2492.  
  2493. =over 2
  2494.  
  2495. =item The dbd_db_FETCH_attrib method
  2496.  
  2497. =cut
  2498.  
  2499. #=POD-Perl-5.6.x=end
  2500.  
  2501. =pod
  2502.  
  2503. This is the counterpart of dbd_db_STORE_attrib, needed for:
  2504.  
  2505.   $value = $dbh->{$key};
  2506.  
  2507. Its prototype is:
  2508.  
  2509.   SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv);
  2510.  
  2511. Unlike all previous methods this returns an SV with the value. Note
  2512. that you should normally execute sv_2mortal, if you return a nonconstant
  2513. value. (Constant values are C<&sv_undef>, C<&sv_no> and C<&sv_yes>.)
  2514.  
  2515. Note, that DBI implements a caching algorithm for attribute values.
  2516. If you think, that an attribute may be fetched, you store it in the
  2517. dbh itself:
  2518.  
  2519.   if (cacheit) /* cache value for later DBI 'quick' fetch? */
  2520.       hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
  2521.  
  2522. =cut
  2523.  
  2524. #=head3 The dbd_st_prepare method
  2525. #=POD-Perl-5.6.x=begin
  2526.  
  2527. =pod
  2528.  
  2529. =back
  2530.  
  2531. =over 2
  2532.  
  2533. =item The dbd_st_prepare method
  2534.  
  2535. =cut
  2536.  
  2537. #=POD-Perl-5.6.x=end
  2538.  
  2539. =pod
  2540.  
  2541. This is the private part of the I<prepare> method. Note that you
  2542. B<must not> really execute the statement here. You may, for example,
  2543. preparse and validate the statement or do similar things.
  2544.  
  2545.   int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement,
  2546.                      SV* attribs);
  2547.  
  2548. A typical, simple, possibility is to do nothing and rely on the perl
  2549. perpare() code that set the Statement attribute on the handle. This
  2550. attribute can then be used by dbd_st_execute.
  2551.  
  2552. If the driver supports placeholders then the NUM_OF_PARAMS attribute
  2553. must be set correctly by dbd_st_prepare:
  2554.  
  2555.   DBIc_NUM_PARAMS(imp_sth) = ...
  2556.  
  2557. If you can, you should also setup attributes like NUM_OF_FIELDS,
  2558. NAME, ... here, but DBI doesn't require that. However, if you do,
  2559. document it.
  2560.  
  2561. In any case you should set the IMPSET flag, as you did in
  2562. I<dbd_db_connect> above:
  2563.  
  2564.   DBIc_IMPSET_on(imp_sth);
  2565.  
  2566. =cut
  2567.  
  2568. #=head3 The dbd_st_execute method
  2569. #=POD-Perl-5.6.x=begin
  2570.  
  2571. =pod
  2572.  
  2573. =back
  2574.  
  2575. =over 2
  2576.  
  2577. =item The dbd_st_execute method
  2578.  
  2579. =cut
  2580.  
  2581. #=POD-Perl-5.6.x=end
  2582.  
  2583. =pod
  2584.  
  2585. This is where a statement will really be executed.
  2586.  
  2587.   int dbd_st_execute(SV* sth, imp_sth_t* imp_sth);
  2588.  
  2589. Note, that you must be aware, that a statement may be executed
  2590. repeatedly.
  2591. Also, you should not expect, that I<finish> will be called between two
  2592. executions, so you'll might need code like the following near the start
  2593. of the function:
  2594.  
  2595.   if (DBIc_ACTIVE(imp_sth))
  2596.       dbd_st_finish(h, imp_sth);
  2597.  
  2598. If your driver supports the binding of parameters (it should!), but the
  2599. database doesn't, you must do it here. This can be done as follows:
  2600.  
  2601.   SV *svp;
  2602.   char* statement = DBD_ATTRIB_GET_PV(h, "Statement", 9, svp, "");
  2603.   int numParam = DBIc_NUM_PARAMS(imp_sth);
  2604.   int i;
  2605.  
  2606.   for (i = 0; i < numParam; i++)
  2607.   {
  2608.       char* value = dbd_db_get_param(sth, imp_sth, i);
  2609.       /* It is your drivers task to implement dbd_db_get_param,    */
  2610.       /* it must be setup as a counterpart of dbd_bind_ph.         */
  2611.       /* Look for '?' and replace it with 'value'.  Difficult      */
  2612.       /* task, note that you may have question marks inside        */
  2613.       /* quotes and comments the like ...  :-(                     */
  2614.       /* See DBD::mysql for an example. (Don't look too deep into  */
  2615.       /* the example, you will notice where I was lazy ...)        */
  2616.   }
  2617.  
  2618. The next thing is you really execute the statement.
  2619. Note that you must set the attributes NUM_OF_FIELDS,
  2620. NAME, etc when the statement is successfully executed if the driver has
  2621. not already done so.
  2622. They may be used even before a potential I<fetchrow>.
  2623. In particular you have to tell DBI the number of fields, that the
  2624. statement has, because it will be used by DBI internally.
  2625. Thus the function will typically ends with:
  2626.  
  2627.   if (isSelectStatement) {
  2628.       DBIc_NUM_FIELDS(imp_sth) = numFields;
  2629.       DBIc_ACTIVE_on(imp_sth);
  2630.   }
  2631.  
  2632. It is important that the ACTIVE flag only be set for C<SELECT> statements
  2633. (or any other statements that can return multiple sets of values from
  2634. the database using a cursor-like mechanism).
  2635. See I<dbd_db_connect> above for more explanations.
  2636.  
  2637. There plans for a preparse function to be provided by DBI, but this has
  2638. not reached fruition yet.
  2639. Meantime, if you want to know how ugly it can get, try looking at the
  2640. I<dbd_ix_preparse> in DBD::Informix I<dbdimp.ec> and the related
  2641. functions in I<iustoken.c> and I<sqltoken.c>.
  2642.  
  2643. =cut
  2644.  
  2645. #=head3 The dbd_st_fetch method
  2646. #=POD-Perl-5.6.x=begin
  2647.  
  2648. =pod
  2649.  
  2650. =back
  2651.  
  2652. =over 2
  2653.  
  2654. =item The dbd_st_fetch method
  2655.  
  2656. =cut
  2657.  
  2658. #=POD-Perl-5.6.x=end
  2659.  
  2660. =pod
  2661.  
  2662. This function fetches a row of data. The row is stored in in an array,
  2663. of SV's that DBI prepares for you. This has two advantages: it is fast
  2664. (you even reuse the SV's, so they don't have to be created after the
  2665. first fetchrow), and it guarantees that DBI handles I<bind_cols> for
  2666. you.
  2667.  
  2668. What you do is the following:
  2669.  
  2670.   AV* av;
  2671.   int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS
  2672.       is constant for this statement. There are drivers where this is
  2673.       not the case! */
  2674.   int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
  2675.   int i;
  2676.  
  2677.   if (!fetch_new_row_of_data(...)) {
  2678.       ... /* check for error or end-of-data */
  2679.       DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */
  2680.       return Nullav;
  2681.   }
  2682.   /* get the fbav (field buffer array value) for this row       */
  2683.   /* it is very important to only call this after you know      */
  2684.   /* that you have a row of data to return.                     */
  2685.   av = DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
  2686.   for (i = 0; i < numFields; i++) {
  2687.       SV* sv = fetch_a_field(..., i);
  2688.       if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) {
  2689.           /*  Remove white space from end (only) of sv  */
  2690.       }
  2691.       sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */
  2692.   }
  2693.   return av;
  2694.  
  2695. There's no need to use a fetch_a_field function returning an SV*.
  2696. It's more common to use your database API functions to fetch the
  2697. data as character strings and use code like this:
  2698.  
  2699.   sv_setpvn(AvARRAY(av)[i], char_ptr, char_count);
  2700.  
  2701. NULL values must be returned as undef. You can use code like this:
  2702.  
  2703.   SvOK_off(AvARRAY(av)[i]);
  2704.  
  2705. The function returns the AV prepared by DBI for success or C<Nullav>
  2706. otherwise.
  2707.  
  2708. =over 4
  2709.  
  2710. *FIX ME* Discuss what happens when there's no more data to fetch.
  2711. Are errors permitted if another fetch occurs after the first fetch
  2712. that reports no more data. (Permitted, not required.)
  2713.  
  2714. =back
  2715.  
  2716. =cut
  2717.  
  2718. #=head3 The dbd_st_finish3 method
  2719. #=POD-Perl-5.6.x=begin
  2720.  
  2721. =pod
  2722.  
  2723. =back
  2724.  
  2725. =over 2
  2726.  
  2727. =item The dbd_st_finish3 method
  2728.  
  2729. =cut
  2730.  
  2731. #=POD-Perl-5.6.x=end
  2732.  
  2733. =pod
  2734.  
  2735. The C<$sth-E<gt>finish> method can be called if the user wishes to
  2736. indicate that no more rows will be fetched even if the database has more
  2737. rows to offer, and the DBI code can call the function when handles are
  2738. being destroyed.
  2739. See the DBI specification for more background details.
  2740. In both circumstances, the DBI code ends up calling the
  2741. C<dbd_st_finish3> method (if you provide a mapping for I<dbd_st_finish3>
  2742. in I<dbdimp.h>), or I<dbd_st_finish> otherwise.
  2743. The difference is that dbd_st_finish3 takes a third argument which is an
  2744. C<int> with the value 1 if it is being called from a destroy method and
  2745. 0 otherwise.
  2746.  
  2747. Note that DBI v1.32 and earlier test on dbd_db_finish3 to call
  2748. dbd_st_finish3; if you provide dbd_st_finish3, either define
  2749. dbd_db_finish3 too, or insist on DBI v1.33 or later.
  2750.  
  2751. All it I<needs> to do is turn off the Active flag for the sth.
  2752. It will only be called by Driver.xst code, if the driver has set ACTIVE
  2753. to on for the sth.
  2754.  
  2755. Outline example:
  2756.  
  2757.   int dbd_st_finish3(SV* sth, imp_sth_t* imp_sth, int from_destroy) {
  2758.       if (DBIc_ACTIVE(imp_sth))
  2759.       {
  2760.           /* close cursor or equivalent action */
  2761.           DBIc_ACTIVE_off(imp_sth);
  2762.       }
  2763.       return 1;
  2764.   }
  2765.  
  2766. The from_destroy parameter is true if dbd_st_finish3 is being called
  2767. from DESTROY - and so the statement is about to be destroyed.
  2768. For many drivers there's no point in doing anything more than turing of
  2769. the Active flag in this case.
  2770.  
  2771. The function returns TRUE for success, FALSE otherwise, but there isn't
  2772. a lot anyone can do to recover if there is an error.
  2773.  
  2774. =cut
  2775.  
  2776. #=head3 The dbd_st_destroy method
  2777. #=POD-Perl-5.6.x=begin
  2778.  
  2779. =pod
  2780.  
  2781. =back
  2782.  
  2783. =over 2
  2784.  
  2785. =item The dbd_st_destroy method
  2786.  
  2787. =cut
  2788.  
  2789. #=POD-Perl-5.6.x=end
  2790.  
  2791. =pod
  2792.  
  2793. This function is the private part of the statement handle destructor.
  2794.  
  2795.   void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth) {
  2796.       ... /* any clean-up that's needed */
  2797.       DBIc_IMPSET_off(imp_sth); /* let DBI know we've done it   */
  2798.   }
  2799.  
  2800. The DBI Driver.xst code will call dbd_st_finish for you, if the sth has
  2801. the ACTIVE flag set, before calling dbd_st_destroy.
  2802.  
  2803. =cut
  2804.  
  2805. #=head3 The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
  2806. #=POD-Perl-5.6.x=begin
  2807.  
  2808. =pod
  2809.  
  2810. =back
  2811.  
  2812. =over 2
  2813.  
  2814. =item The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
  2815.  
  2816. =cut
  2817.  
  2818. #=POD-Perl-5.6.x=end
  2819.  
  2820. =pod
  2821.  
  2822. These functions correspond to dbd_db_STORE and dbd_db_FETCH attrib
  2823. above, except that they are for statement handles.
  2824. See above.
  2825.  
  2826.   int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv,
  2827.                           SV* valuesv);
  2828.   SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv);
  2829.  
  2830. =cut
  2831.  
  2832. #=head3 The dbd_bind_ph method
  2833. #=POD-Perl-5.6.x=begin
  2834.  
  2835. =pod
  2836.  
  2837. =back
  2838.  
  2839. =over 2
  2840.  
  2841. =item The dbd_bind_ph method
  2842.  
  2843. =cut
  2844.  
  2845. #=POD-Perl-5.6.x=end
  2846.  
  2847. =pod
  2848.  
  2849. This function is internally used by the I<bind_param> method, the
  2850. I<bind_param_inout> method and by the DBI Driver.xst code if C<execute>
  2851. is called with any bind parameters.
  2852.  
  2853.   int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param,
  2854.                    SV *value, IV sql_type, SV *attribs,
  2855.                    int is_inout, IV maxlen);
  2856.  
  2857. The I<param> argument holds an IV with the parameter number (1, 2, ...).
  2858. The I<value> argument is the parameter value and I<sql_type> is its type.
  2859.  
  2860. If your driver does not support bind_param_inout then you should
  2861. ignore I<maxlen> and croak if I<is_inout> is TRUE.
  2862.  
  2863. If your driver I<does> support bind_param_inout then you should
  2864. note that I<value> is the SV I<after> dereferencing the reference
  2865. passed to bind_param_inout.
  2866.  
  2867. In drivers of simple databases the function will, for example, store
  2868. the value in a parameter array and use it later in I<dbd_st_execute>.
  2869. See the I<DBD::mysql> driver for an example.
  2870.  
  2871. =cut
  2872.  
  2873. #=head3 Implementing bind_param_inout support
  2874. #=POD-Perl-5.6.x=begin
  2875.  
  2876. =pod
  2877.  
  2878. =back
  2879.  
  2880. =over 2
  2881.  
  2882. =item Implementing bind_param_inout support
  2883.  
  2884. =cut
  2885.  
  2886. #=POD-Perl-5.6.x=end
  2887.  
  2888. =pod
  2889.  
  2890. To provide support for parameters bound by reference rather than by
  2891. value, the driver must do a number of things.  First, and most
  2892. importantly, it must note the references and stash them in its own
  2893. driver structure.  Secondly, when a value is bound to a column, the
  2894. driver must discard any previous reference bound to the column.  On
  2895. each execute, the driver must evaluate the references and internally
  2896. bind the values resulting from the references.  This is only applicable
  2897. if the user writes:
  2898.  
  2899.   $sth->execute;
  2900.  
  2901. If the user writes:
  2902.  
  2903.   $sth->execute(@values);
  2904.  
  2905. then DBI automatically calls the binding code for each element of
  2906. @values.  These calls are indistinguishable from explicit user calls to
  2907. bind_param.
  2908.  
  2909. =cut
  2910.  
  2911. #=POD-Perl-5.6.x=begin
  2912.  
  2913. =pod
  2914.  
  2915. =back
  2916.  
  2917. =cut
  2918.  
  2919. #=POD-Perl-5.6.x=end
  2920.  
  2921. =pod
  2922.  
  2923. =head2 C/XS version of Makefile.PL
  2924.  
  2925. The I<Makefile.PL> file for a C/XS driver is similar to the code needed
  2926. for a pure Perl driver, but there are a number of extra bits of
  2927. information needed by the build system.
  2928. For example, the attributes list passed to C<WriteMakefile> needs to
  2929. specify the object files that need to be compiled and built into the
  2930. shared object (DLL).
  2931. This is often, but not necessarily, just dbdimp.o (unless that should be
  2932. dbdimp.obj because you're building on MS Windows).
  2933. Note that you can reliably determine the extension of the object files
  2934. from the $Config{obj_ext} values, and there are many other useful pieces
  2935. of configuration information lurking in that hash.
  2936. You get access to it with:
  2937.  
  2938.     use Config;
  2939.  
  2940. =head2 Methods which do not need to be written
  2941.  
  2942. The DBI code implements the majority of the methods which are
  2943. accessed using the notation DBI->function(), the only exceptions being
  2944. DBI->connect() and DBI->data_sources() which require support from the
  2945. driver.
  2946.  
  2947. The DBI code implements the following documented driver, database and
  2948. statement functions which do not need to be written by the DBD driver
  2949. writer.
  2950.  
  2951. =over 4
  2952.  
  2953. =item $dbh->do()
  2954.  
  2955. The default implementation of this function prepares, executes and
  2956. destroys the statement.  This can be replaced if there is a better
  2957. way to implement this, such as EXECUTE IMMEDIATE which can
  2958. sometimes be used if there are no parameters.
  2959.  
  2960. =item $h->errstr()
  2961.  
  2962. =item $h->err()
  2963.  
  2964. =item $h->state()
  2965.  
  2966. =item $h->trace()
  2967.  
  2968. The DBD driver does not need to worry about these routines at all.
  2969.  
  2970. =item $h->{ChopBlanks}
  2971.  
  2972. This attribute needs to be honured during fetch operations, but does
  2973. not need to be handled by the attribute handling code.
  2974.  
  2975. =item $h->{RaiseError}
  2976.  
  2977. The DBD driver does not need to worry about this attribute at all.
  2978.  
  2979. =item $h->{PrintError}
  2980.  
  2981. The DBD driver does not need to worry about this attribute at all.
  2982.  
  2983. =item $sth->bind_col()
  2984.  
  2985. Assuming the driver uses the DBIc_DBISTATE(imp_xxh)->get_fbav() function (C drivers,
  2986. see below), or the $sth->_set_fbav($data) method (Perl drivers)
  2987. the driver does not need to do anything about this routine.
  2988.  
  2989. =item $sth->bind_columns()
  2990.  
  2991. Regardless of whether the driver uses DBIc_DBISTATE(imp_xxh)->get_fbav(), the driver
  2992. does not need to do anything about this routine as it simply
  2993. iteratively calls $sth->bind_col().
  2994.  
  2995. =back
  2996.  
  2997. The DBI code implements a default implementation of the following
  2998. functions which do not need to be written by the DBD driver writer
  2999. unless the default implementation is incorrect for the Driver.
  3000.  
  3001. =over 4
  3002.  
  3003. =item $dbh->quote()
  3004.  
  3005. This should only be written if the database does not accept the ANSI
  3006. SQL standard for quoting strings, with the string enclosed in single
  3007. quotes and any embedded single quotes replaced by two consecutive
  3008. single quotes.
  3009.  
  3010. For the two argument form of quote, you need to implement the
  3011. C<type_info> method to provide the information that quote needs.
  3012.  
  3013. =item $dbh->ping()
  3014.  
  3015. This should be implemented as a simple efficient way to determine
  3016. whether the connection to the database is still alive. Typically
  3017. code like this:
  3018.  
  3019.   sub ping {
  3020.       my $dbh = shift;
  3021.       $sth = $dbh->prepare_cached(q{
  3022.           select * from A_TABLE_NAME where 1=0
  3023.       }) or return 0;
  3024.       $sth->execute or return 0;
  3025.       $sth->finish;
  3026.       return 1;
  3027.   }
  3028.  
  3029. where A_TABLE_NAME is the name of a table that always exists (such as a
  3030. database system catalogue).
  3031.  
  3032. =back
  3033.  
  3034. =head1 METADATA METHODS
  3035.  
  3036. The exposition above ignores the DBI MetaData methods.
  3037. The metadata methods are all associated with a database handle.
  3038.  
  3039. =head2 Using DBI::DBD::Metadata
  3040.  
  3041. The DBI::DBD::Metadata module is a good semi-automatic way for the developer of a DBD module to
  3042. write the get_info and type_info functions quickly and accurately.
  3043.  
  3044. =cut
  3045.  
  3046. #=head3 Generating the get_info method
  3047. #=POD-Perl-5.6.x=begin
  3048.  
  3049. =pod
  3050.  
  3051. =over 2
  3052.  
  3053. =item Generating the get_info method
  3054.  
  3055. =cut
  3056.  
  3057. #=POD-Perl-5.6.x=end
  3058.  
  3059. =pod
  3060.  
  3061. Prior to DBI v1.33, this existed as the method write_getinfo_pm in the
  3062. DBI::DBD module.
  3063. From DBI v1.33, it exists as the method write_getinfo_pm in the
  3064. DBI::DBD::Metadata module.
  3065. This discussion assumes you have DBI v1.33 or later.
  3066.  
  3067. You examine the documentation for write_getinfo_pm using:
  3068.  
  3069.     perldoc DBI::DBD::Metadata
  3070.  
  3071. To use it, you need a Perl DBI driver for your database which implements
  3072. the get_info method.
  3073. In practice, this means you need to install DBD::ODBC, an ODBC driver
  3074. manager, and an ODBC driver for your database.
  3075. With the pre-requisites in place, you might type:
  3076.  
  3077.     perl -MDBI::DBD::Metadata -e write_getinfo_pm \
  3078.             dbi:ODBC:foo_db username password Driver
  3079.  
  3080. The procedure writes to standard output the code that should be added to
  3081. your Driver.pm file and the code that should be written to
  3082. lib/DBD/Driver/GetInfo.pm.
  3083. You should review the output to ensure that it is sensible.
  3084.  
  3085. =cut
  3086.  
  3087. #=head3 Generating the type_info method
  3088. #=POD-Perl-5.6.x=begin
  3089.  
  3090. =pod
  3091.  
  3092. =back
  3093.  
  3094. =over 2
  3095.  
  3096. =item Generating the type_info method
  3097.  
  3098. =cut
  3099.  
  3100. #=POD-Perl-5.6.x=end
  3101.  
  3102. =pod
  3103.  
  3104. Given the idea of the write_getinfo_pm method, it was not hard to devise
  3105. a parallel method, write_typeinfo_pm, which does the analogous job for the
  3106. DBI type_info_all metadata method.
  3107. The the write_typeinfo_pm method was added to DBI v1.33.
  3108.  
  3109. You examine the documentation for write_typeinfo_pm using:
  3110.  
  3111.     perldoc DBI::DBD::Metadata
  3112.  
  3113. The setup is exactly analogous to the mechanism descibed in
  3114. L</Generating the get_info method>
  3115. With the pre-requisites in place, you might type:
  3116.  
  3117.     perl -MDBI::DBD::Metadata -e write_typeinfo \
  3118.             dbi:ODBC:foo_db username password Driver
  3119.  
  3120. The procedure writes to standard output the code that should be added to
  3121. your Driver.pm file and the code that should be written to
  3122. lib/DBD/Driver/TypeInfo.pm.
  3123. You should review the output to ensure that it is sensible.
  3124.  
  3125. =back
  3126.  
  3127. =head2 Writing DBD::Driver::db::get_info
  3128.  
  3129. If you use the DBI::DBD::Metadata module, then the code you need is
  3130. generated for you.
  3131.  
  3132. If you decide not to use the DBI::DBD::Metadata module, you should
  3133. probably borrow the code from a driver that has done so (eg
  3134. DBD::Informix from version 1.05 onwards) and crib the code from there,
  3135. or look at the code that generates that module and follow that.
  3136. The method in Driver.pm will be very simple; the method in
  3137. lib/DBD/Driver/GetInfo.pm is not very much more complex unless your DBMS itself is
  3138. much more complex.
  3139.  
  3140. Note that some of the DBI utility methods rely on information from the
  3141. get_info method to perform their operations correctly.
  3142. See, for example, the quote_identifier and quote methods, discussed
  3143. below.
  3144.  
  3145. =head2 Writing DBD::Driver::db::type_info_all
  3146.  
  3147. If you use the DBI::DBD::Metadata module, then the code you need is
  3148. generated for you.
  3149.  
  3150. If you decide not to use the DBI::DBD::Metadata module, you should
  3151. probably borrow the code from a driver that has done so (eg
  3152. DBD::Informix from version 1.05 onwards) and crib the code from there,
  3153. or look at the code that generates that module and follow that.
  3154. The method in Driver.pm will be very simple; the method in
  3155. lib/DBD/Driver/TypeInfo.pm is not very much more complex unless your DBMS
  3156. itself is much more complex.
  3157.  
  3158. =head2 Writing DBD::Driver::db::type_info
  3159.  
  3160. The guidelines on writing this method are still not really clear.
  3161. No sample implementation is available.
  3162.  
  3163. =head2 Writing DBD::Driver::db::table_info
  3164.  
  3165. =over 4
  3166.  
  3167. *FIX ME* The guidelines on writing this method have not been written yet.
  3168. No sample implementation is available.
  3169.  
  3170. =back
  3171.  
  3172. =head2 Writing DBD::Driver::db::column_info
  3173.  
  3174. =over 4
  3175.  
  3176. *FIX ME* The guidelines on writing this method have not been written yet.
  3177. No sample implementation is available.
  3178.  
  3179. =back
  3180.  
  3181. =head2 Writing DBD::Driver::db::primary_key_info
  3182.  
  3183. =over 4
  3184.  
  3185. *FIX ME* The guidelines on writing this method have not been written yet.
  3186. No sample implementation is available.
  3187.  
  3188. =back
  3189.  
  3190. =head2 Writing DBD::Driver::db::primary_key
  3191.  
  3192. =over 4
  3193.  
  3194. *FIX ME* The guidelines on writing this method have not been written yet.
  3195. No sample implementation is available.
  3196.  
  3197. =back
  3198.  
  3199. =head2 Writing DBD::Driver::db::foreign_key_info
  3200.  
  3201. =over 4
  3202.  
  3203. *FIX ME* The guidelines on writing this method have not been written yet.
  3204. No sample implementation is available.
  3205.  
  3206. =back
  3207.  
  3208. =head2 Writing DBD::Driver::db::tables
  3209.  
  3210. This method generates an array of names in a format suitable for being
  3211. embedded in SQL statements in places where a table name is expected.
  3212.  
  3213. If your database hews close enough to the SQL standard or if you have
  3214. implemented an appropriate table_info function and and the appropriate
  3215. quote_identifier function, then the DBI default version of this method
  3216. will work for your driver too.
  3217.  
  3218. Otherwise, you have to write a function yourself, such as:
  3219.  
  3220.     sub tables
  3221.     {
  3222.         my($dbh, $cat, $sch, $tab, $typ) = @_;
  3223.         my(@res);
  3224.         my($sth) = $dbh->table_info($cat, $sch, $tab, $typ);
  3225.         my(@arr);
  3226.         while (@arr = $sth->fetchrow_array)
  3227.         {
  3228.             push @res, $dbh->quote_identifier($arr[0], $arr[1], $arr[2]);
  3229.         }
  3230.         return @res;
  3231.     }
  3232.  
  3233. See also the default implementation in DBI.pm.
  3234.  
  3235. =head2 Writing DBD::Driver::db::quote
  3236.  
  3237. This method takes a value and converts it into a string suitable for
  3238. embedding in an SQL statement as a string literal.
  3239.  
  3240. If your DBMS accepts the SQL standard notation for strings (single
  3241. quotes around the string as a whole with any embedded single quotes
  3242. doubled up), then you do not need to write this method as DBI provides a
  3243. default method that does it for you.
  3244. If your DBMS uses an alternative notation or escape mechanism, then you
  3245. need to provide an equivalent function.
  3246. For example, suppose your DBMS used C notation with double quotes around
  3247. the string and backslashes escaping both double quotes and backslashes
  3248. themselves.
  3249. Then you might write the function as:
  3250.  
  3251.     sub quote
  3252.     {
  3253.         my($dbh, $str) = @_;
  3254.         $str =~ s/["\\]/\\$&/gmo;
  3255.         return qq{"$str"};
  3256.     }
  3257.  
  3258. Handling newlines and other control characters is left as an exercise
  3259. for the reader.
  3260.  
  3261. This sample method ignores the $data_type indicator which is the
  3262. optional second argument to the method.
  3263.  
  3264. =head2 Writing DBD::Driver::db::quote_identifier
  3265.  
  3266. This method is called to ensure that the name of the given table (or
  3267. other database object) can be embedded into an SQL statement without
  3268. danger of misinterpretation.
  3269. The result string should be usable in the text of an SQL statement as
  3270. the identifier for a table.
  3271.  
  3272. If your DBMS accepts the SQL standard notation for quoted identifiers
  3273. (which uses double quotes around the identifier as a whole, with any
  3274. embedded double quotes doubled up) and accepts "schema"."identifier"
  3275. (and "catalog"."schema"."identifier" when a catalog is specified), then
  3276. you do not need to write this method as DBI provides a default method
  3277. that does it for you.
  3278. In fact, even if your DBMS does not handle exactly that notation but you
  3279. have implemented the get_info method and it gives the correct responses,
  3280. then it will work for you.
  3281. If your database is fussier, then you need to implement your own version
  3282. of the function.
  3283.  
  3284. For example, DBD::Informix has to deal with an environment variable
  3285. DELIMIDENT.
  3286. If it is not set, then the DBMS treats names enclosed in double quotes
  3287. as strings rather than names, which is usually a syntax error.
  3288. Additionally, the catalog portion of the name is separated from the
  3289. schema and table by a different delimiter (colon instead of dot), and
  3290. the catalog portion is never enclosed in quotes.
  3291. (Fortunately, valid strings for the catalog will never contain weird
  3292. characters that might need to be escaped, unless you count dots, dashes,
  3293. slashes and at-signs as weird.)
  3294. Finally, an Informix database can contain objects that cannot be
  3295. accessed because they were created by a user with the DELIMIDENT
  3296. environment variable set, but the current user does not have it set.
  3297. By design choice, the quote_identifier method encloses those identifiers
  3298. in double quotes anyway, which generally triggers a syntax error, and
  3299. the metadata methods which generate lists of tables etc omit those
  3300. identifiers from the result sets.
  3301.  
  3302.     sub quote_identifier
  3303.     {
  3304.         my($dbh, $cat, $sch, $obj) = @_;
  3305.         my($rv) = "";
  3306.         my($qq) = (defined $ENV{DELIMIDENT}) ? '"' : '';
  3307.         $rv .= qq{$cat:} if (defined $cat);
  3308.         if (defined $sch)
  3309.         {
  3310.             if ($sch !~ m/^\w+$/o)
  3311.             {
  3312.                 $qq = '"';
  3313.                 $sch =~ s/$qq/$qq$qq/gm;
  3314.             }
  3315.             $rv .= qq{$qq$sch$qq.};
  3316.         }
  3317.         if (defined $obj)
  3318.         {
  3319.             if ($obj !~ m/^\w+$/o)
  3320.             {
  3321.                 $qq = '"';
  3322.                 $obj =~ s/$qq/$qq$qq/gm;
  3323.             }
  3324.             $rv .= qq{$qq$obj$qq};
  3325.         }
  3326.         return $rv;
  3327.     }
  3328.  
  3329. Handling newlines and other control characters is left as an exercise
  3330. for the reader.
  3331.  
  3332. Note that there is an optional fourth parameter to this function which
  3333. is a reference to a hash of attributes; this sample implementation
  3334. ignores that.
  3335. This sample implementation also ignores the single-argument variant of
  3336. the method.
  3337.  
  3338. =head1 WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE
  3339.  
  3340. Study Oraperl.pm (supplied with DBD::Oracle) and Ingperl.pm (supplied
  3341. with DBD::Ingres) and the corresponding dbdimp.c files for ideas.
  3342.  
  3343. Note that the emulation code sets $dbh->{CompatMode} = 1; for each
  3344. connection so that the internals of the driver can implement behaviour
  3345. compatible with the old interface when dealing with those handles.
  3346.  
  3347. =head2 Setting emulation perl variables
  3348.  
  3349. For example, ingperl has a $sql_rowcount variable. Rather than try
  3350. to manually update this in Ingperl.pm it can be done faster in C code.
  3351. In dbd_init():
  3352.  
  3353.   sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI);
  3354.  
  3355. In the relevant places do:
  3356.  
  3357.   if (DBIc_COMPAT(imp_sth))     /* only do this for compatibility mode handles */
  3358.       sv_setiv(sql_rowcount, the_row_count);
  3359.  
  3360. =head1 OTHER MISCELLANEOUS INFORMATION
  3361.  
  3362. =head2 The imp_xyz_t types
  3363.  
  3364. Any handle has a corresponding C structure filled with private data.
  3365. Some of this data is reserved for use by DBI (except for using the
  3366. DBIc macros below), some is for you. See the description of the
  3367. I<dbdimp.h> file above for examples. The most functions in dbdimp.c
  3368. are passed both the handle C<xyz> and a pointer to C<imp_xyz>. In
  3369. rare cases, however, you may use the following macros:
  3370.  
  3371. =over 2
  3372.  
  3373. =item D_imp_dbh(dbh)
  3374.  
  3375. Given a function argument I<dbh>, declare a variable I<imp_dbh> and
  3376. initialize it with a pointer to the handles private data. Note: This
  3377. must be a part of the function header, because it declares a variable.
  3378.  
  3379. =item D_imp_sth(sth)
  3380.  
  3381. Likewise for statement handles.
  3382.  
  3383. =item D_imp_xxx(h)
  3384.  
  3385. Given any handle, declare a variable I<imp_xxx> and initialize it
  3386. with a pointer to the handles private data. It is safe, for example,
  3387. to cast I<imp_xxx> to C<imp_dbh_t*>, if DBIc_TYPE(imp_xxx) == DBIt_DB.
  3388. (You can also call sv_derived_from(h, "DBI::db"), but that's much
  3389. slower.)
  3390.  
  3391. =item D_imp_dbh_from_sth
  3392.  
  3393. Given a imp_sth, declare a variable I<imp_dbh> and initialize it with a
  3394. pointer to the parent database handle's implementors structure.
  3395.  
  3396. =back
  3397.  
  3398. =head2 Using DBIc_IMPSET_on
  3399.  
  3400. The driver code which initializes a handle should use DBIc_IMPSET_on()
  3401. as soon as its state is such that the cleanup code must be called.
  3402. When this happens is determined by your driver code.
  3403.  
  3404. Failure to call this can lead to corruption of data structures.
  3405. For example, DBD::Informix maintains a linked list of database handles
  3406. in the driver, and within each handle, a linked list of statements.
  3407. Once a statement is added to the linked list, it is crucial that it is
  3408. cleaned up (removed from the list).
  3409. When DBIc_IMPSET_on() was being called too late, it was able to cause
  3410. all sorts of problems.
  3411.  
  3412. =head2 Using DBIc_is(), DBIc_has(), DBIc_on() and DBIc_off()
  3413.  
  3414. Once upon a long time ago, the only way of handling the internal DBI
  3415. boolean flags/attributes was through macros such as:
  3416.  
  3417.   DBIc_WARN       DBIc_WARN_on        DBIc_WARN_off
  3418.   DBIc_COMPAT     DBIc_COMPAT_on      DBIc_COMPAT_off
  3419.  
  3420. Each of these took an imp_xxh pointer as an argument.
  3421.  
  3422. Since then, new attributes have been added such as ChopBlanks,
  3423. RaiseError and PrintError, and these do not have the full set of
  3424. macros.
  3425. The approved method for handling these is now the four macros:
  3426.  
  3427.   DBIc_is(imp, flag)
  3428.   DBIc_has(imp, flag)    an alias for DBIc_is
  3429.   DBIc_on(imp, flag)
  3430.   DBIc_off(imp, flag)
  3431.  
  3432. Consequently, the DBIc_XXXXX family of macros is now mostly deprecated
  3433. and new drivers should avoid using them, even though the older drivers
  3434. will probably continue to do so for quite a while yet. However...
  3435.  
  3436. There is an I<important exception> to that. The ACTIVE and IMPSET
  3437. flags should be set via the DBIc_ACTIVE_on and DBIc_IMPSET_on macros,
  3438. and unset via the DBIc_ACTIVE_off and DBIc_IMPSET_off macros.
  3439.  
  3440. =head2 Using the get_fbav() method
  3441.  
  3442. B<THIS IS CRITICAL> for C/XS drivers.
  3443.  
  3444. The $sth->bind_col() and $sth->bind_columns() documented in the DBI
  3445. specification do not have to be implemented by the driver writer because
  3446. DBI takes care of the details for you.
  3447. However, the key to ensuring that bound columns work is to call the
  3448. function DBIc_DBISTATE(imp_xxh)->get_fbav() in the code which fetches a
  3449. row of data.
  3450. This returns an AV, and each element of the AV contains the SV which
  3451. should be set to contain the returned data.
  3452.  
  3453. The pure Perl equivalent is the $sth->_set_fbav($data) method, as
  3454. described in the part on pure Perl drivers.
  3455.  
  3456. =head1 SUBCLASSING DBI DRIVERS
  3457.  
  3458. This is definitely an open subject. It can be done, as demonstrated by
  3459. the I<DBD::File> driver, but it is not as simple as one might think.
  3460.  
  3461. (Note that this topic is different from subclassing the DBI. For an
  3462. example of that, see the t/subclass.t file supplied with the DBI.)
  3463.  
  3464. The main problem is that the dbh's and sth's that your I<connect> and
  3465. I<prepare> methods return are not instances of your I<DBD::Driver::db>
  3466. or I<DBD::Driver::st> packages, they are not even derived from it.
  3467. Instead they are instances of the I<DBI::db> or I<DBI::st> classes or
  3468. a derived subclass. Thus, if you write a method I<mymethod> and do a
  3469.  
  3470.   $dbh->mymethod()
  3471.  
  3472. then the autoloader will search for that method in the package I<DBI::db>.
  3473. Of course you can instead to a
  3474.  
  3475.   $dbh->func('mymethod')
  3476.  
  3477. and that will indeed work, even if I<mymethod> is inherited, but not
  3478. without additional work. Setting C<@ISA> is not sufficient.
  3479.  
  3480. =head2 Overwriting methods
  3481.  
  3482. The first problem is, that the I<connect> method has no idea of
  3483. subclasses. For example, you cannot implement base class and subclass
  3484. in the same file: The I<install_driver> method wants to do a
  3485.  
  3486.   require DBD::Driver;
  3487.  
  3488. In particular, your subclass B<has> to be a separate driver, from
  3489. the view of DBI, and you cannot share driver handles.
  3490.  
  3491. Of course that's not much of a problem. You should even be able
  3492. to inherit the base classes I<connect> method. But you cannot
  3493. simply overwrite the method, unless you do something like this,
  3494. quoted from I<DBD::CSV>:
  3495.  
  3496.   sub connect ($$;$$$) {
  3497.       my ($drh, $dbname, $user, $auth, $attr) = @_;
  3498.  
  3499.       my $this = $drh->DBD::File::dr::connect($dbname, $user, $auth, $attr);
  3500.       if (!exists($this->{csv_tables})) {
  3501.           $this->{csv_tables} = {};
  3502.       }
  3503.  
  3504.       $this;
  3505.   }
  3506.  
  3507. Note that we cannot do a
  3508.  
  3509.   $srh->SUPER::connect($dbname, $user, $auth, $attr);
  3510.  
  3511. as we would usually do in a an OO environment, because $drh is an instance
  3512. of I<DBI::dr>. And note, that the I<connect> method of I<DBD::File> is
  3513. able to handle subclass attributes. See the description of Pure Perl
  3514. drivers above.
  3515.  
  3516. It is essential that you always call superclass method in the above
  3517. manner. However, that should do.
  3518.  
  3519. =head2 Attribute handling
  3520.  
  3521. Fortunately the DBI specifications allow a simple, but still performant way of
  3522. handling attributes. The idea is based on the convention that any
  3523. driver uses a prefix I<driver_> for its private methods. Thus it's
  3524. always clear whether to pass attributes to the super class or not.
  3525. For example, consider this STORE method from the I<DBD::CSV> class:
  3526.  
  3527.   sub STORE {
  3528.       my ($dbh, $attr, $val) = @_;
  3529.       if ($attr !~ /^driver_/) {
  3530.           return $dbh->DBD::File::db::STORE($attr, $val);
  3531.       }
  3532.       if ($attr eq 'driver_foo') {
  3533.       ...
  3534.   }
  3535.  
  3536. =cut
  3537.  
  3538. use Exporter ();
  3539. use Config qw(%Config);
  3540. use Carp;
  3541. use Cwd;
  3542. use strict;
  3543. use vars qw(
  3544.     @ISA @EXPORT
  3545.     $is_dbi
  3546. );
  3547.  
  3548. BEGIN { if ($^O eq 'VMS') {
  3549.     require vmsish;
  3550.     import  vmsish;
  3551.     require VMS::Filespec;
  3552.     import  VMS::Filespec;
  3553. }}
  3554.  
  3555. @ISA = qw(Exporter);
  3556.  
  3557. @EXPORT = qw(
  3558.     dbd_dbi_dir
  3559.     dbd_dbi_arch_dir
  3560.     dbd_edit_mm_attribs
  3561.     dbd_postamble
  3562. );
  3563.  
  3564. BEGIN {
  3565.     $is_dbi = (-r 'DBI.pm' && -r 'DBI.xs' && -r 'DBIXS.h');
  3566.     require DBI unless $is_dbi;
  3567. }
  3568.  
  3569. sub _cwd_check {
  3570.     my $cwd = cwd();
  3571.     return unless $cwd =~ /$Config{path_sep}/;
  3572.     warn "*** Warning: Path separator characters (`$Config{path_sep}') in the current directory path ($cwd) may cause problems\a\n";
  3573.     sleep 2;
  3574. }
  3575.  
  3576. sub dbd_edit_mm_attribs {
  3577.     # this both edits the attribs in-place and returns the flattened attribs
  3578.     my $mm_attr = shift;
  3579.     my $dbd_attr = shift || {};
  3580.     croak "dbd_edit_mm_attribs( \%makemaker [, \%other ]): too many parameters"
  3581.     if @_;
  3582.     _cwd_check();
  3583.  
  3584.     # decide what needs doing
  3585.  
  3586.     # do whatever needs doing
  3587.     if ($dbd_attr->{create_pp_tests}) {
  3588.     # XXX need to convert this to work within the generated Makefile
  3589.     # so 'make' creates them and 'make clean' deletes them
  3590.     die "Can't create DBI::PurePerl tests unless 't' directory exists"
  3591.         unless -d 't';
  3592.     opendir DIR, 't';
  3593.     my @tests = grep { /\.t$/ } readdir DIR;
  3594.     closedir DIR;
  3595.     foreach my $test (sort @tests) {
  3596.         next if $test =~ /^zz_.*_pp\.t$/;
  3597.         $test =~ s/\.t$//;
  3598.         my $pp_test = "t/zz_${test}_pp.t";
  3599.         my $usethr = ($test =~ /(\d+|\b)thr/ && $] >= 5.008 && $Config{useithreads});
  3600.         printf "Creating extra DBI::PurePerl test: $pp_test %s\n",
  3601.         ($usethr) ? "(use threads)" : "";
  3602.         open PPT, ">$pp_test" or warn "Can't create $pp_test: $!";
  3603.         print PPT "#!perl -w\n";
  3604.         print PPT "use threads;\n" if $usethr;
  3605.         print PPT "\$ENV{DBI_PUREPERL}=2;\n";
  3606.         print PPT "do 't/$test.t' or warn \$!;\n";
  3607.         print PPT 'die if $@;'."\n";
  3608.         print PPT "exit 0\n";
  3609.         close PPT or warn "Error writing $pp_test: $!";
  3610.     }
  3611.     }
  3612.     return %$mm_attr;
  3613. }
  3614.  
  3615. sub dbd_dbi_dir {
  3616.     return '.' if $is_dbi;
  3617.     my $dbidir = $INC{'DBI.pm'} || die "DBI.pm not in %INC!";
  3618.     $dbidir =~ s:/DBI\.pm$::;
  3619.     return $dbidir;
  3620. }
  3621.  
  3622. sub dbd_dbi_arch_dir {
  3623.     _cwd_check();
  3624.     return '$(INST_ARCHAUTODIR)' if $is_dbi;
  3625.     my $dbidir = dbd_dbi_dir();
  3626.     my @try = map { "$_/auto/DBI" } @INC;
  3627.     my @xst = grep { -f "$_/Driver.xst" } @try;
  3628.     Carp::croak("Unable to locate Driver.xst in @try") unless @xst;
  3629.     Carp::carp( "Multiple copies of Driver.xst found in: @xst") if @xst > 1;
  3630.     print "Using DBI $DBI::VERSION (for perl $] on $Config{archname}) installed in $xst[0]\n";
  3631.     return $xst[0];
  3632. }
  3633.  
  3634. sub dbd_postamble {
  3635.     my $self = shift;
  3636.     _cwd_check();
  3637.     my $dbidir = dbd_dbi_dir();
  3638.     my $xstdir = dbd_dbi_arch_dir();
  3639.     my $xstfile= '$(DBI_INSTARCH_DIR)/Driver.xst';
  3640.     my $xstf_h = '$(DBI_INSTARCH_DIR)/Driver_xst.h';
  3641.     my $QQ = ( $Config{make} eq 'dmake') ? '"' : '';
  3642.     if ($^O eq 'VMS') {
  3643.     $dbidir = vmsify($dbidir.'/');
  3644.     $xstdir = vmsify($xstdir.'/') unless $is_dbi;
  3645.     $xstfile= '$(DBI_INSTARCH_DIR)Driver.xst';
  3646.     $xstf_h = '$(DBI_INSTARCH_DIR)Driver_xst.h';
  3647.     }
  3648.  
  3649.     # we must be careful of quotes, expecially for Win32 here.
  3650.     '
  3651. # --- This section was generated by DBI::DBD::dbd_postamble()
  3652. DBI_INST_DIR='.$dbidir.'
  3653. DBI_INSTARCH_DIR='.$xstdir.'
  3654. DBI_DRIVER_XST='.$xstfile.'
  3655.  
  3656. # The main dependancy (technically correct but probably not used)
  3657. $(BASEEXT).c: $(BASEEXT).xsi
  3658.  
  3659. # This dependancy is needed since MakeMaker uses the .xs.o rule
  3660. $(BASEEXT)$(OBJ_EXT): $(BASEEXT).xsi
  3661.  
  3662. $(BASEEXT).xsi: $(DBI_DRIVER_XST) '.$xstf_h.'
  3663.     $(PERL) -p -e "s/~DRIVER~/$(BASEEXT)/g" $(DBI_DRIVER_XST) > $(BASEEXT).xsi
  3664.  
  3665. # these two keep make -j4 working
  3666. '.$QQ.'$(DBI_DRIVER_XST)'.$QQ.' :: pm_to_blib
  3667.     $(NOECHO) $(NOOP)
  3668.  
  3669. '.$QQ.$xstf_h.$QQ.' :: pm_to_blib
  3670.     $(NOECHO) $(NOOP)
  3671.  
  3672. # ---
  3673. ';
  3674. }
  3675.  
  3676. __END__
  3677.  
  3678. =head1 AUTHORS
  3679.  
  3680. Jonathan Leffler <jleffler@us.ibm.com> (previously <jleffler@informix.com>),
  3681. Jochen Wiedmann <joe@ispsoft.de>,
  3682. Steffen Goeldner <sgoeldner@cpan.org>,
  3683. and Tim Bunce <dbi-users@perl.org>.
  3684.  
  3685. =cut
  3686.