home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / DBD.pm < prev    next >
Encoding:
Perl POD Document  |  2004-06-26  |  110.2 KB  |  3,794 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.21 $ =~ /(\d+)\.(\d+)/o);
  6.  
  7.  
  8. # $Id: DBD.pm,v 11.21 2004/02/01 11:16:16 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.21 $
  62.   $Date: 2004/02/01 11:16:16 $
  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.21 $ ' =~ /(\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<set_err> method:
  981.  
  982.   $h->set_err($err, $errmsg, $state);
  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->set_err($err, $errmsg, $state) 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. Where reasonable use $h->SUPER::foo() to call the DBI's method in
  1262. some or all cases and just wrap your custom behavior around that.
  1263.  
  1264. If you want to use private trace flags you'll probably want to be
  1265. able to set them by name. To do that you'll need to define a
  1266. parse_trace_flag() method (note that's parse_trace_flag not parse_trace_flags).
  1267.  
  1268.   sub parse_trace_flag {
  1269.       my ($h, $name) = @_;
  1270.       return 0x01000000 if $name eq 'foo';
  1271.       return 0x02000000 if $name eq 'bar';
  1272.       return 0x04000000 if $name eq 'baz';
  1273.       return 0x08000000 if $name eq 'boo';
  1274.       return 0x10000000 if $name eq 'bop';
  1275.       return $h->SUPER::parse_trace_flag($name);
  1276.   }
  1277.  
  1278. All private flag names must be lowercase, and all private flags
  1279. must be in the top 8 of the 32 bits.
  1280.  
  1281. =cut
  1282.  
  1283. #=head3 The DBD::Driver::st package
  1284. #=POD-Perl-5.6.x=begin
  1285.  
  1286. =pod
  1287.  
  1288. =back
  1289.  
  1290. =over 2
  1291.  
  1292. =item The DBD::Driver::st package
  1293.  
  1294. =cut
  1295.  
  1296. #=POD-Perl-5.6.x=end
  1297.  
  1298. =pod
  1299.  
  1300. =cut
  1301.  
  1302. #=head4 The execute method
  1303. #=POD-Perl-5.6.x=begin
  1304.  
  1305. =pod
  1306.  
  1307. =back
  1308.  
  1309. =over 2
  1310.  
  1311. =item The execute method
  1312.  
  1313. =cut
  1314.  
  1315. #=POD-Perl-5.6.x=end
  1316.  
  1317. =pod
  1318.  
  1319. This is perhaps the most difficult method because we have to consider
  1320. parameter bindings here. We present a simplified implementation by
  1321. using the I<drv_params> attribute from above:
  1322.  
  1323.   package DBD::Driver::st;
  1324.  
  1325.   $DBD::Driver::st::imp_data_size = 0;
  1326.  
  1327.   sub bind_param
  1328.   {
  1329.       my ($sth, $pNum, $val, $attr) = @_;
  1330.       my $type = (ref $attr) ? $attr->{TYPE} : $attr;
  1331.       if ($type) {
  1332.           my $dbh = $sth->{Database};
  1333.           $val = $dbh->quote($sth, $type);
  1334.       }
  1335.       my $params = $sth->FETCH('drv_params');
  1336.       $params->[$pNum-1] = $val;
  1337.       1;
  1338.   }
  1339.  
  1340.   sub execute
  1341.   {
  1342.       my ($sth, @bind_values) = @_;
  1343.  
  1344.       # start of by finishing any previous execution if still active
  1345.       $sth->finish if $sth->{Active};
  1346.  
  1347.       my $params = (@bind_values) ?
  1348.           \@bind_values : $sth->FETCH('drv_params');
  1349.       my $numParam = $sth->FETCH('NUM_OF_PARAMS');
  1350.       return $sth->set_err(1, "Wrong number of parameters")
  1351.           if @$params != $numParam;
  1352.       my $statement = $sth->{'Statement'};
  1353.       for (my $i = 0;  $i < $numParam;  $i++) {
  1354.           $statement =~ s/?/$params->[$i]/; # XXX doesn't deal with quoting etc!
  1355.       }
  1356.       # Do anything ... we assume that an array ref of rows is
  1357.       # created and store it:
  1358.       $sth->{'drv_data'} = $data;
  1359.       $sth->{'drv_rows'} = @$data; # number of rows
  1360.       $sth->STORE('NUM_OF_FIELDS') = $numFields;
  1361.       @$data || '0E0';
  1362.   }
  1363.  
  1364. There are a number of things you should note here.
  1365. We setup the NUM_OF_FIELDS attribute
  1366. here, because this is essential for I<bind_columns> to work.
  1367. We use attribute I<$sth->{'Statement'}> which we created
  1368. within I<prepare>. The attribute I<$sth->{'Database'}>, which is
  1369. nothing else than the I<dbh>, was automatically created by DBI.
  1370.  
  1371. Finally note that (as specified in the DBI specification) we return the
  1372. string '0E0' instead of the number 0, so that the result tests true but
  1373. equal to zero.
  1374.  
  1375.   $sth->execute() or die $sth->errstr;
  1376.  
  1377. =cut
  1378.  
  1379. #=head4 Fetching data
  1380. #=POD-Perl-5.6.x=begin
  1381.  
  1382. =pod
  1383.  
  1384. =back
  1385.  
  1386. =over 2
  1387.  
  1388. =item Fetching data
  1389.  
  1390. =cut
  1391.  
  1392. #=POD-Perl-5.6.x=end
  1393.  
  1394. =pod
  1395.  
  1396. We should not implement the methods I<fetchrow_array>, I<fetchall_arrayref>,
  1397. ... because these are already part of DBI.
  1398. All we need is the method
  1399. I<fetchrow_arrayref>:
  1400.  
  1401.   sub fetchrow_arrayref
  1402.   {
  1403.       my ($sth) = @_;
  1404.       my $data = $sth->FETCH('drv_data');
  1405.       my $row = shift @$data;
  1406.       if (!$row) {
  1407.           $sth->{Active} = 0; # mark as no longer active 
  1408.           return undef;
  1409.       }
  1410.       if ($sth->FETCH('ChopBlanks')) {
  1411.           map { $_ =~ s/\s+$//; } @$row;
  1412.       }
  1413.       return $sth->_set_fbav($row);
  1414.   }
  1415.   *fetch = \&fetchrow_arrayref; # required alias for fetchrow_arrayref
  1416.  
  1417.   sub rows { shift->FETCH('drv_rows') }
  1418.  
  1419. Note the use of the method I<_set_fbav>: This is required so that
  1420. I<bind_col> and I<bind_columns> work.
  1421.  
  1422. If an error occurs which leaves the $sth in a state where remaining rows
  1423. can't be fetched then Active should be turned off
  1424. before the method returns.
  1425.  
  1426. =cut
  1427.  
  1428. #=head4 Statement attributes
  1429. #=POD-Perl-5.6.x=begin
  1430.  
  1431. =pod
  1432.  
  1433. =back
  1434.  
  1435. =over 2
  1436.  
  1437. =item Statement attributes
  1438.  
  1439. =cut
  1440.  
  1441. #=POD-Perl-5.6.x=end
  1442.  
  1443. =pod
  1444.  
  1445. The main difference between dbh and sth attributes is, that you
  1446. should implement a lot of attributes here that are required by
  1447. the DBI, such as I<NAME>, I<NULLABLE>, I<TYPE>, ...
  1448.  
  1449. Besides that the STORE and FETCH methods are mainly the same
  1450. as above for dbh's.
  1451.  
  1452. =cut
  1453.  
  1454. #=head4 Other statement methods
  1455. #=POD-Perl-5.6.x=begin
  1456.  
  1457. =pod
  1458.  
  1459. =back
  1460.  
  1461. =over 2
  1462.  
  1463. =item Other statement methods
  1464.  
  1465. =cut
  1466.  
  1467. #=POD-Perl-5.6.x=end
  1468.  
  1469. =pod
  1470.  
  1471. A trivial C<finish> method to discard the stored data and do
  1472. $sth->SUPER::finish;
  1473.  
  1474. A C<table_info> method to return details of available tables.
  1475.  
  1476. A C<type_info_all> method to return details of supported types.
  1477.  
  1478. If you've defined a parse_trace_flag() method in ::db you'll also want
  1479. it in ::st, so just alias it in:
  1480.  
  1481.   *parse_trace_flag = \&DBD::foo:db::parse_trace_flag;
  1482.  
  1483. And perhaps some other methods that are not part of the DBI
  1484. specification, in particular to make metadata available.
  1485. Remember that they must have names that begin with your drivers
  1486. registered prefix so they can be installed using install_method().
  1487.  
  1488.  
  1489. =cut
  1490.  
  1491. #=POD-Perl-5.6.x=begin
  1492.  
  1493. =pod
  1494.  
  1495. =back
  1496.  
  1497. =cut
  1498.  
  1499. #=POD-Perl-5.6.x=end
  1500.  
  1501. =pod
  1502.  
  1503. =head2 Tests
  1504.  
  1505. The test process should conform as closely as possibly to the Perl
  1506. standard test harness.
  1507.  
  1508. In particular, most (all) of the tests should be run in the t sub-directory,
  1509. and should simply produce an 'ok' when run under 'make test'.
  1510. For details on how this is done, see the Camel book and the section in
  1511. Chapter 7, "The Standard Perl Library" on L<Test::Harness>.
  1512.  
  1513. The tests may need to adapt to the type of database which is being
  1514. used for testing, and to the privileges of the user testing the
  1515. driver.
  1516.  
  1517. The DBD::Informix test code has to adapt in a number of places to the
  1518. type of database to which it is connected as different Informix
  1519. databases have different capabilities.
  1520. For example, some of the tests are for databases without transaction
  1521. logs; others are for databases with a transaction log.
  1522. Some versions of the server have support for blobs, or stored
  1523. procedures, or user-defined data types, and others do not.
  1524. When a complete file of tests must be skipped, you can provide a reason
  1525. in a pseudo-comment:
  1526.  
  1527.     if ($no_transactions_available)
  1528.     {
  1529.         print "1..0 # Skip: No transactions available\n";
  1530.         exit 0;
  1531.     }
  1532.  
  1533. Consider downloading the DBD::Informix code and look at the code in
  1534. DBD/Informix/TestHarness.pm which is used throughout the
  1535. DBD::Informix tests in the t sub-directory.
  1536.  
  1537. =head1 CREATING A C/XS DRIVER
  1538.  
  1539. Creating a new C/XS driver from scratch will always be a daunting task.
  1540. You can and should greatly simplify your task by taking a good
  1541. reference driver implementation and modifying that to match the
  1542. database product for which you are writing a driver.
  1543.  
  1544. The de facto reference driver has been the one for DBD::Oracle written
  1545. by Tim Bunce, who is also the author of the DBI package. The DBD::Oracle
  1546. module is a good example of a driver implemented around a C-level API.
  1547.  
  1548. Nowadays it it seems better to base on DBD::ODBC, another driver
  1549. maintained by Tim and Jeff Urlwin, because it offers a lot of metadata
  1550. and seems to become the guideline for the future development. (Also as
  1551. DBD::Oracle digs deeper into the Oracle 8 OCI interface it'll get even
  1552. more hairy than it is now.)
  1553.  
  1554. The DBD::Informix driver is one driver implemented using embedded SQL
  1555. instead of a function-based API.
  1556. DBD::Ingres may also be worth a look.
  1557.  
  1558. =head2 C/XS version of Driver.pm
  1559.  
  1560. A lot of the code in the Driver.pm file is very similar to the code for pure Perl modules
  1561. - see above.  However,
  1562. there are also some subtle (and not so subtle) differences, including:
  1563.  
  1564. =over 8
  1565.  
  1566. =item *
  1567.  
  1568. The variables $DBD::File::{dr|db|st}::imp_data_size are not defined
  1569. here, but in the XS code, because they declare the size of certain
  1570. C structures.
  1571.  
  1572. =item *
  1573.  
  1574. Some methods are typically moved to the XS code, in particular
  1575. I<prepare>, I<execute>, I<disconnect>, I<disconnect_all> and the STORE
  1576. and FETCH methods.
  1577.  
  1578. =item *
  1579.  
  1580. Other methods are still part of C<Driver.pm>, but have callbacks to
  1581. the XS code.
  1582.  
  1583. =item *
  1584.  
  1585. If the driver-specific parts of the imp_drh_t structure need to be
  1586. formally initialized (which does not seem to be a common requirement),
  1587. then you need to add a call to an appropriate XS function in the driver
  1588. method of DBD::Driver::driver, and you define the corresponding function
  1589. in Driver.xs, and you define the C code in dbdimp.c and the prototype in
  1590. dbdimp.h.
  1591.  
  1592. For example, DBD::Informix has such a requirement, and adds the
  1593. following call after the call to _new_drh in Informix.pm:
  1594.  
  1595.   DBD::Informix::dr::driver_init($drh);
  1596.  
  1597. and the following code in Informix.xs:
  1598.  
  1599.   # Initialize the DBD::Informix driver data structure
  1600.   void
  1601.   driver_init(drh)
  1602.       SV *drh
  1603.       CODE:
  1604.       ST(0) = dbd_ix_dr_driver_init(drh) ? &sv_yes : &sv_no;
  1605.  
  1606. and the code in dbdimp.h declares:
  1607.  
  1608.   extern int dbd_ix_dr_driver_init(SV *drh);
  1609.  
  1610. and the code in dbdimp.ec (equivalent to dbdimp.c) defines:
  1611.  
  1612.   /* Formally initialize the DBD::Informix driver structure */
  1613.   int
  1614.   dbd_ix_dr_driver(SV *drh)
  1615.   {
  1616.       D_imp_drh(drh);
  1617.       imp_drh->n_connections = 0;       /* No active connections */
  1618.       imp_drh->current_connection = 0;  /* No current connection */
  1619.       imp_drh->multipleconnections = (ESQLC_VERSION >= 600) ? True : False;
  1620.       dbd_ix_link_newhead(&imp_drh->head);  /* Empty linked list of connections */
  1621.       return 1;
  1622.   }
  1623.  
  1624. DBD::Oracle has a similar requirement but gets around it by checking
  1625. whether the private data part of the driver handle is all zeroed out,
  1626. rather than add extra functions.
  1627.  
  1628. =back
  1629.  
  1630. Now let's take a closer look at an excerpt from Oracle.pm (revised
  1631. heavily to remove idiosyncrasies) as an example.
  1632. We also ignore things that are already discussed for pure Perl drivers.
  1633.  
  1634. =cut
  1635.  
  1636. #=head3 The connect method
  1637. #=POD-Perl-5.6.x=begin
  1638.  
  1639. =pod
  1640.  
  1641. =over 2
  1642.  
  1643. =item The connect method
  1644.  
  1645. =cut
  1646.  
  1647. #=POD-Perl-5.6.x=end
  1648.  
  1649. =pod
  1650.  
  1651. The connect method is the database handle constructor.
  1652. You could write either of two versions of this method: either one which
  1653. takes connection attributes (new code) and one which ignores them (old
  1654. code only).
  1655. If you ignore the connection attributes, then you omit all mention of
  1656. the $auth variable (which is a reference to a hash of attributes), and
  1657. the XS system manages the differences for you.
  1658.  
  1659.   sub connect
  1660.   {
  1661.       my ($drh, $dbname, $user, $auth, $attr) = @_;
  1662.  
  1663.       # Some database specific verifications, default settings
  1664.       # and the like following here. This should only include
  1665.       # syntax checks or similar stuff where it's legal to
  1666.       # 'die' in case of errors.
  1667.  
  1668.       my $dbh = DBI::_new_dbh($drh, {
  1669.               'Name'   => $dbname,
  1670.           })
  1671.           or return undef;
  1672.  
  1673.       # Call the driver-specific function _login in Driver.xs file which
  1674.       # calls the DBMS-specific function(s) to connect to the database,
  1675.       # and populate internal handle data.
  1676.       DBD::Driver::db::_login($dbh, $dbname, $user, $auth, $attr)
  1677.           or return undef;
  1678.  
  1679.       $dbh;
  1680.   }
  1681.  
  1682. This is mostly the same as in the pure Perl case, the exception being
  1683. the use of the private I<_login> callback, which is the function that
  1684. will really connect to the database.
  1685. It is implemented in Driver.xst (you should not implement it) and calls
  1686. I<dbd_db_login6> from I<dbdimp.c>.
  1687. See below for details.
  1688.  
  1689. =over 4
  1690.  
  1691. *FIX ME* Discuss removing attributes from hash reference as an optimization
  1692. to skip later calls to $dbh->STORE made by DBI->connect.
  1693.  
  1694. *FIX ME* Discuss removing attributes in Perl code.
  1695.  
  1696. *FIX ME* Discuss removing attributes in C code.
  1697.  
  1698. =back
  1699.  
  1700. =cut
  1701.  
  1702. #=head3 The disconnect_all method
  1703. #=POD-Perl-5.6.x=begin
  1704.  
  1705. =pod
  1706.  
  1707. =back
  1708.  
  1709. =over 2
  1710.  
  1711. =item The disconnect_all method
  1712.  
  1713. =cut
  1714.  
  1715. #=POD-Perl-5.6.x=end
  1716.  
  1717. =pod
  1718.  
  1719. *FIX ME* T.B.S
  1720.  
  1721. =cut
  1722.  
  1723. #=head3 The data_sources method
  1724. #=POD-Perl-5.6.x=begin
  1725.  
  1726. =pod
  1727.  
  1728. =back
  1729.  
  1730. =over 2
  1731.  
  1732. =item The data_sources method
  1733.  
  1734. =cut
  1735.  
  1736. #=POD-Perl-5.6.x=end
  1737.  
  1738. =pod
  1739.  
  1740. If your I<data_sources> method can be implemented in pure Perl, then do
  1741. so because it is easier than doing it in XS code (see the section above
  1742. for pure Perl drivers).
  1743. If your I<data_sources> method must call onto compiled functions, then
  1744. you will need to define dbd_dr_data_sources in your dbdimp.h file, which
  1745. will trigger Driver.xst (in DBI v1.33 or greater) to generate the XS
  1746. code that calls your actual C function (see the discussion below for
  1747. details) and you do not code anything in Driver.pm to handle it.
  1748.  
  1749. =cut
  1750.  
  1751. #=head3 The prepare method
  1752. #=POD-Perl-5.6.x=begin
  1753.  
  1754. =pod
  1755.  
  1756. =back
  1757.  
  1758. =over 2
  1759.  
  1760. =item The prepare method
  1761.  
  1762. =cut
  1763.  
  1764. #=POD-Perl-5.6.x=end
  1765.  
  1766. =pod
  1767.  
  1768. The prepare method is the statement handle constructor, and most of it
  1769. is not new.
  1770. Like the I<connect> method, it now has a C callback:
  1771.  
  1772.   package DBD::Driver::db; # ====== DATABASE ======
  1773.   use strict;
  1774.  
  1775.   sub prepare
  1776.   {
  1777.       my ($dbh, $statement, $attribs) = @_;
  1778.  
  1779.       # create a 'blank' sth
  1780.       my $sth = DBI::_new_sth($dbh, {
  1781.           'Statement' => $statement,
  1782.           })
  1783.           or return undef;
  1784.  
  1785.       # Call the driver-specific function _prepare in Driver.xs file
  1786.       # which calls the DBMS-specific function(s) to prepare a statement
  1787.       # and populate internal handle data.
  1788.       DBD::Driver::st::_prepare($sth, $statement, $attribs)
  1789.           or return undef;
  1790.       $sth;
  1791.   }
  1792.  
  1793. =cut
  1794.  
  1795. #=head3 The execute method
  1796. #=POD-Perl-5.6.x=begin
  1797.  
  1798. =pod
  1799.  
  1800. =back
  1801.  
  1802. =over 2
  1803.  
  1804. =item The execute method
  1805.  
  1806. =cut
  1807.  
  1808. #=POD-Perl-5.6.x=end
  1809.  
  1810. =pod
  1811.  
  1812. *FIX ME* T.B.S
  1813.  
  1814. =cut
  1815.  
  1816. #=head3 The fetchrow_arrayref method
  1817. #=POD-Perl-5.6.x=begin
  1818.  
  1819. =pod
  1820.  
  1821. =back
  1822.  
  1823. =over 2
  1824.  
  1825. =item The fetchrow_arrayref method
  1826.  
  1827. =cut
  1828.  
  1829. #=POD-Perl-5.6.x=end
  1830.  
  1831. =pod
  1832.  
  1833. *FIX ME* T.B.S
  1834.  
  1835. =cut
  1836.  
  1837. #=head3 Other methods?
  1838. #=POD-Perl-5.6.x=begin
  1839.  
  1840. =pod
  1841.  
  1842. =back
  1843.  
  1844. =over 2
  1845.  
  1846. =item Other methods?
  1847.  
  1848. =cut
  1849.  
  1850. #=POD-Perl-5.6.x=end
  1851.  
  1852. =pod
  1853.  
  1854. *FIX ME* T.B.S
  1855.  
  1856. =cut
  1857.  
  1858. #=POD-Perl-5.6.x=begin
  1859.  
  1860. =pod
  1861.  
  1862. =back
  1863.  
  1864. =cut
  1865.  
  1866. #=POD-Perl-5.6.x=end
  1867.  
  1868. =pod
  1869.  
  1870. =head2 Driver.xs
  1871.  
  1872. Driver.xs should look something like this:
  1873.  
  1874.   #include "Driver.h"
  1875.  
  1876.   DBISTATE_DECLARE;
  1877.  
  1878.   INCLUDE: Driver.xsi
  1879.  
  1880.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::dr
  1881.  
  1882.   /* Non-standard drh XS methods following here, if any.       */
  1883.   /* If none (the usual case), omit the MODULE line above too. */
  1884.  
  1885.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::db
  1886.  
  1887.   /* Non-standard dbh XS methods following here, if any.       */
  1888.   /* Currently this includes things like _list_tables from     */
  1889.   /* DBD::mSQL and DBD::mysql.                                 */
  1890.  
  1891.   MODULE = DBD::Driver    PACKAGE = DBD::Driver::st
  1892.  
  1893.   /* Non-standard sth XS methods following here, if any.       */
  1894.   /* In particular this includes things like _list_fields from */
  1895.   /* DBD::mSQL and DBD::mysql for accessing metadata.          */
  1896.  
  1897. Note especially the include of I<Driver.xsi> here: DBI inserts stub
  1898. functions for almost all private methods here which will typically do
  1899. much work for you.
  1900. Wherever you really have to implement something, it will call a private
  1901. function in I<dbdimp.c>, and this is what you have to implement.
  1902.  
  1903. You need to set up an extra routine if your driver needs to export
  1904. constants of its own, analogous to the SQL types available when you say:
  1905.  
  1906.   use DBI qw(:sql_types);
  1907.  
  1908. *FIX ME* T.B.S
  1909.  
  1910. =head2 Driver.h
  1911.  
  1912. Driver.h is very simple and the operational contents should look like this:
  1913.  
  1914.   #ifndef DRIVER_H_INCLUDED
  1915.   #define DRIVER_H_INCLUDED
  1916.  
  1917.   #define NEED_DBIXS_VERSION 93    /* 93 for DBI versions 1.00 to 1.32 */
  1918.  
  1919.   #include <DBIXS.h>      /* installed by the DBI module  */
  1920.  
  1921.   #include "dbdimp.h"
  1922.  
  1923.   #include "dbivport.h"   /* see below                    */
  1924.  
  1925.   #include <dbd_xsh.h>    /* installed by the DBI module  */
  1926.  
  1927.   #endif /* DRIVER_H_INCLUDED */
  1928.  
  1929. The C<DBIXS.h> header defines most of the interesting information that
  1930. the writer of a driver needs.
  1931. The file C<dbd_xsh.h> header provides prototype declarations for the C
  1932. functions that you might decide to implement.
  1933. Note that you should normally only define one of I<dbd_db_login> and
  1934. I<dbd_db_login6> unless you are intent on supporting really old versions of
  1935. DBI (prior to DBI 1.06) as well as modern versions.
  1936. The only standard, DBI-mandated functions that you need write are those
  1937. specified in the dbd_xsh.h header.
  1938. You might also add extra driver-specific functions in Driver.xs.
  1939.  
  1940. The dbivport.h file should be I<copied> from the latest DBI release into
  1941. your distribution each time you enhance your driver to use new features
  1942. for which the DBI is offering backwards compatibility via dbivport.h.
  1943.  
  1944. Its job is to allow you to enhance your code to work with the latest
  1945. DBI API while still allowing your driver to be compiled and used
  1946. with older versions of the DBI. For example, when the DBIh_SET_ERR_CHAR
  1947. macro was added to DBI 1.41 in an emulation of it was added to dbivport.h.
  1948.  
  1949. Copying dbivport.h into your driver distribution and #including it
  1950. in Driver.h, as shown above, lets you enhance your driver to use
  1951. the new DBIh_SET_ERR_CHAR macro even with versions of the DBI earlier
  1952. than 1.41. This makes users happy and your life easier.
  1953.  
  1954. Always read the notes in dbivport.h to check for any limitations
  1955. in the emulation that you should be aware of.
  1956.  
  1957.  
  1958. =head2 Implementation header dbdimp.h
  1959.  
  1960. This header file has two jobs:
  1961.  
  1962. First it defines data structures for your private part of the handles.
  1963.  
  1964. Second it defines macros that rename the generic names like
  1965. I<dbd_db_login> to database specific names like I<ora_db_login>. This
  1966. avoids name clashes and enables use of different drivers when you work
  1967. with a statically linked perl.
  1968.  
  1969. It also will have the important task of disabling XS methods that you
  1970. don't want to implement.
  1971.  
  1972. Finally, the macros will also be used to select alternate
  1973. implementations of some functions.
  1974. For example, the I<dbd_db_login> function is not passed the attribute
  1975. hash.
  1976. Since DBI v1.06, if a I<dbd_db_login6> macro is defined (for a function
  1977. with 6 arguments), it will be used instead with the attribute hash
  1978. passed as the sixth argument.
  1979.  
  1980. People used to just pick Oracle's dbdimp.c and use the same names,
  1981. structures and types.
  1982. I strongly recommend against that.
  1983. At first glance this saves time, but your implementation will be less
  1984. readable.
  1985. It was just hell when I had to separate DBI specific parts, Oracle
  1986. specific parts, mSQL specific parts and mysql specific parts in
  1987. DBD::mysql's I<dbdimp.h> and I<dbdimp.c>.
  1988. (DBD::mysql was a port of DBD::mSQL which was based on DBD::Oracle.)
  1989. [Seconded, based on the experience taking DBD::Informix apart, even
  1990. though the version inherited in 1996 was only based on DBD::Oracle.]
  1991.  
  1992. This part of the driver is I<your exclusive part>.
  1993. Rewrite it from scratch, so it will be clean and short: in other words,
  1994. a better piece of code.
  1995. (Of course keep an eye on other people's work.)
  1996.  
  1997.   struct imp_drh_st {
  1998.       dbih_drc_t com;           /* MUST be first element in structure   */
  1999.       /* Insert your driver handle attributes here */
  2000.   };
  2001.  
  2002.   struct imp_dbh_st {
  2003.       dbih_dbc_t com;           /* MUST be first element in structure   */
  2004.       /* Insert your database handle attributes here */
  2005.   };
  2006.  
  2007.   struct imp_sth_st {
  2008.       dbih_stc_t com;           /* MUST be first element in structure   */
  2009.       /* Insert your statement handle attributes here */
  2010.   };
  2011.  
  2012.   /*  Rename functions for avoiding name clashes; prototypes are  */
  2013.   /*  in dbd_xst.h                                                */
  2014.   #define dbd_init         drv_dr_init
  2015.   #define dbd_db_login6    drv_db_login
  2016.   #define dbd_db_do        drv_db_do
  2017.   ... many more here ...
  2018.  
  2019. These structures implement your private part of the handles.
  2020. You I<have> to use the name I<imp_dbh_{dr|db|st}> and the first field
  2021. I<must> be of type I<dbih_drc_t|_dbc_t|_stc_t> and I<must> be called
  2022. C<com>.
  2023. You should never access these fields directly, except by using the
  2024. I<DBIc_xxx> macros below.
  2025.  
  2026. =head2 Implementation source dbdimp.c
  2027.  
  2028. Conventionally, I<dbdimp.c> is the main implementation file (but
  2029. DBD::Informix calls the file dbdimp.ec).
  2030. This section includes a short note on each function that is used in the
  2031. Driver.xsi template and thus B<has> to be implemented.
  2032.  
  2033. Of course, you will probably also need to implement other support
  2034. functions, which should usually be file static if the are placed in
  2035. I<dbdimp.c>.
  2036. If they are placed in other files, you need to list those files in
  2037. Makefile.PL (and MANIFEST) to handle them correctly.
  2038.  
  2039. It is wise to adhere to a namespace convention for your functions to
  2040. avoid conflicts.
  2041. For example, for a driver with prefix "drv", you might call externally
  2042. visible functions "dbd_drv_xxxx".
  2043. You should also avoid non-constant global variables as much as possible
  2044. to improve the support for threading.
  2045.  
  2046. Since Perl 5.6 requires support for function prototypes (ANSI or ISO or
  2047. Standard C), you should write your code using function prototypes too.
  2048. Although technically DBI still supports Perl 5.005_03, which did not
  2049. mandate prototype support from the C compiler, the only platform where
  2050. prototypes are a problem is on HP-UX with the bundled C compiler (which
  2051. is strictly K&R).
  2052. The solution for that is to get a copy of the GNU Compiler Collection
  2053. (GCC, aka the GNU C Compiler) for HP-UX.
  2054.  
  2055. It is possible to use either the unmapped names such as C<dbd_init> or
  2056. the mapped names such as C<dbd_ix_dr_init> in the C<dbdimp.c> file.
  2057. DBD::Informix uses the mapped names which makes it easier to identify
  2058. where to look for linkage problems at runtime (which will report errors
  2059. using the mapped names).
  2060. Most other drivers, and in particular DBD::Oracle, use the unmapped
  2061. names in the source code which makes it a little easier to compare code
  2062. between drivers and eases discussions on the dbi-dev mailing list.
  2063. The majority of the code fragments here will use the unmapped names.
  2064.  
  2065. Ultimately, you should provide implementations for most fo the functions
  2066. listed in the I<dbd_xsh.h> header.
  2067. The exceptions are optional functions (such as I<dbd_st_rows>) and those
  2068. functions with alternative signatures, such as I<dbd_db_login6> and
  2069. I<dbd_db_login>.
  2070. Then you should only implement one of the alternatives, and generally
  2071. the newer one of the alternatives.
  2072.  
  2073. =cut
  2074.  
  2075. #=head3 The dbd_init method
  2076. #=POD-Perl-5.6.x=begin
  2077.  
  2078. =pod
  2079.  
  2080. =over 2
  2081.  
  2082. =item The dbd_init method
  2083.  
  2084. =cut
  2085.  
  2086. #=POD-Perl-5.6.x=end
  2087.  
  2088. =pod
  2089.  
  2090.   #include "Driver.h"
  2091.  
  2092.   DBISTATE_DECLARE;
  2093.  
  2094.   void dbd_init(dbistate_t* dbistate)
  2095.   {
  2096.       DBISTATE_INIT;  /*  Initialize the DBI macros  */
  2097.   }
  2098.  
  2099. The C<dbd_init> function will be called when your driver is first
  2100. loaded; the bootstrap command in DBD::Driver::dr::driver triggers this,
  2101. and the call is generated in the BOOT section of Driver.xst.
  2102. These statements are needed to allow your driver to use the DBI macros.
  2103. They will include your private header file I<dbdimp.h> in turn.
  2104. Note that DBISTATE_INIT requires the name of the argument to I<dbd_init>
  2105. to be called I<dbistate>.
  2106.  
  2107. =cut
  2108.  
  2109. #=head3 The dbd_drv_error method
  2110. #=POD-Perl-5.6.x=begin
  2111.  
  2112. =pod
  2113.  
  2114. =back
  2115.  
  2116. =over 2
  2117.  
  2118. =item The dbd_drv_error method
  2119.  
  2120. =cut
  2121.  
  2122. #=POD-Perl-5.6.x=end
  2123.  
  2124. =pod
  2125.  
  2126. You need a function to record errors so DBI can access them properly.
  2127. You can call it whatever you like, but we'll call it C<dbd_drv_error>
  2128. here.
  2129. The argument list depends on your database software; different systems
  2130. provide different ways to get at error information.
  2131.  
  2132.   static void dbd_drv_error(SV *h, int rc, const char *what)
  2133.   {
  2134.  
  2135. Note that I<h> is a generic handle, may it be a driver handle, a
  2136. database or a statement handle.
  2137.  
  2138.       D_imp_xxh(h);
  2139.  
  2140. This macro will declare and initialize a variable I<imp_xxh> with
  2141. a pointer to your private handle pointer. You may cast this to
  2142. to I<imp_drh_t>, I<imp_dbh_t> or I<imp_sth_t>.
  2143.  
  2144. To record the error correctly, equivalent to the set_err() method,
  2145. use one of the DBIh_SET_ERR_CHAR(...) or DBIh_SET_ERR_SV(...) macros,
  2146. which were added in DBI 1.41:
  2147.  
  2148.   DBIh_SET_ERR_SV(h, imp_xxh, err, errstr, state, method);
  2149.   DBIh_SET_ERR_CHAR(h, imp_xxh, err_c, err_i, errstr, state, method);
  2150.  
  2151. For DBIh_SET_ERR_SV the err, errstr, state, and method parameters are SV*.
  2152. For DBIh_SET_ERR_CHAR the err_c, errstr, state, method are char*.
  2153. The err_i parameter is an IV that's used instead of err_c is err_c is Null.
  2154. The method parameter can be ignored.
  2155.  
  2156. The DBIh_SET_ERR_CHAR macro is usually the simplest to use when you
  2157. just have an integer error code and an error message string:
  2158.  
  2159.   DBIh_SET_ERR_CHAR(h, imp_xxh, Nullch, rc, what, Nullch, Nullch);
  2160.  
  2161. As you can see, any parameters that aren't relevant to you can be Null.
  2162.  
  2163. To make drivers compatible with DBI < 1.41 you should be using dbivport.h
  2164. as described in L</Driver.h> above.
  2165.  
  2166. The (obsolete) macros such as DBIh_EVENT2 should be removed from drivers.
  2167.  
  2168. The names I<dbis> and I<DBIS>, which were used in previous versions of this document,
  2169. should be replaced with the C<DBIc_STATE(imp_xxh)> macro.
  2170.  
  2171. The name DBILOGFP, which was also used in previous  versions of this document, should be
  2172. replaced by DBIc_LOGPIO(imp_xxh).
  2173.  
  2174. Your code should not call the C C<E<lt>stdio.hE<gt>> I/O functions; you should use
  2175. C<PerlIO_printf>() as shown:
  2176.  
  2177.       if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
  2178.           PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar %s: %s\n",
  2179.               foo, neatsvpv(errstr,0));
  2180.  
  2181. That's the first time we see how tracing works within a DBI
  2182. driver.  Make use of this as often as you can! But don't output anything
  2183. at a trace level less than 3. Levels 1 and 2 are reserved for the DBI.
  2184.  
  2185. You can define up to 8 private trace flags using the top 8 bits of
  2186. DBIc_TRACE_FLAGS(imp), that is: 0xFF000000. See the parse_trace_flag() method
  2187. elsewhere in this document.
  2188.  
  2189. =cut
  2190.  
  2191. #=head3 The dbd_dr_data_sources method
  2192. #=POD-Perl-5.6.x=begin
  2193.  
  2194. =pod
  2195.  
  2196. =back
  2197.  
  2198. =over 2
  2199.  
  2200. =item The dbd_dr_data_sources method
  2201.  
  2202. =cut
  2203.  
  2204. #=POD-Perl-5.6.x=end
  2205.  
  2206. =pod
  2207.  
  2208. This method is optional; the support for it was added in DBI v1.33.
  2209.  
  2210. As noted in the discussion of Driver.pm, if the data sources can be
  2211. determined by pure Perl code, do it that way.
  2212. If, as in DBD::Informix, the information is obtained by a C function
  2213. call, then you need to define a function that matches the prototype:
  2214.  
  2215.   extern AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attrs);
  2216.  
  2217. An outline implementation for DBD::Informix follows, assuming that the
  2218. sqgetdbs() function call shown will return up to 100 databases names,
  2219. with the pointers to each name in the array dbsname and the name strings
  2220. themselves being stores in dbsarea.
  2221. The actual DBD::Informix implementation has a number of extra lines of
  2222. code, logs function entry and exit, reports the error from sqgetdbs(),
  2223. and uses #define'd constatnts for the array sizes.
  2224.  
  2225.   AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr)
  2226.   {
  2227.       int ndbs;
  2228.       int i;
  2229.       char *dbsname[100];
  2230.       char  dbsarea[10000];
  2231.       AV *av = Nullav;
  2232.  
  2233.       if (sqgetdbs(&ndbs, dbsname, 100, dbsarea, sizeof(dbsarea)) == 0)
  2234.       {
  2235.           av = NewAV();
  2236.           av_extend(av, (I32)ndbs);
  2237.           sv_2mortal((SV *)av);
  2238.           for (i = 0; i < ndbs; i++)
  2239.             av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i]));
  2240.       }
  2241.       return(av);
  2242.   }
  2243.  
  2244. =cut
  2245.  
  2246. #=head3 The dbd_db_login6 method
  2247. #=POD-Perl-5.6.x=begin
  2248.  
  2249. =pod
  2250.  
  2251. =back
  2252.  
  2253. =over 2
  2254.  
  2255. =item The dbd_db_login6 method
  2256.  
  2257. =cut
  2258.  
  2259. #=POD-Perl-5.6.x=end
  2260.  
  2261. =pod
  2262.  
  2263.   int dbd_db_login6(SV* dbh, imp_dbh_t* imp_dbh, char* dbname,
  2264.                    char* user, char* auth, SV *attr);
  2265.  
  2266. This function will really connect to the database.
  2267. The argument I<dbh> is the database handle.
  2268. I<imp_dbh> is the pointer to the handles private data, as is I<imp_xxx>
  2269. in I<dbd_drv_error> above.
  2270. The arguments I<dbname>, I<user>, I<auth> and I<attr> correspond to the
  2271. arguments of the driver handle's I<connect> method.
  2272.  
  2273. You will quite often use database specific attributes here, that are
  2274. specified in the DSN.
  2275. I recommend you parse the DSN (using Perl) within the I<connect> method
  2276. and pass the segments of the DSN via the attributes parameter through
  2277. I<_login> to I<dbd_db_login6>.
  2278. Here's how you fetch them; as an example we use I<hostname> attribute,
  2279. which can be up to 12 characters long excluding null terminator:
  2280.  
  2281.   SV** svp;
  2282.   STRLEN len;
  2283.   char* hostname;
  2284.  
  2285.   if ( (svp = DBD_ATTRIB_GET_SVP(attr, "drv_hostname", 12)) && SvTRUE(*svp)) {
  2286.       hostname = SvPV(*svp, len);
  2287.       DBD__ATTRIB_DELETE(attr, "drv_hostname", 12); /* avoid later STORE */
  2288.   } else {
  2289.       hostname = "localhost";
  2290.   }
  2291.  
  2292. Note that you can also obtain standard attributes such as AutoCommit and
  2293. ChopBlanks from the attributes parameter, using DBD_ATTRIB_GET_IV for
  2294. integer attributes.
  2295. If, for example, your database does not support transactions but
  2296. AutoCommit is set off (requesting transaction support), then you can
  2297. emulate a 'failure to connect'.
  2298.  
  2299. Now you should really connect to the database.
  2300. In general, if the connection fails, it is best to ensure that all
  2301. allocated resources are released so that the handle does not need to be
  2302. destroyed separately.
  2303. If you are successful (and possibly even if you fail but you have
  2304. allocated some resources), you should use the following macros:
  2305.  
  2306.   DBIc_IMPSET_on(imp_dbh);
  2307.  
  2308. This indicates that the driver (implementor) has allocated resources in
  2309. the imp_dbh structure and that the implementors private dbd_db_destroy
  2310. function should be called when the handle is destroyed.
  2311.  
  2312.   DBIc_ACTIVE_on(imp_dbh);
  2313.  
  2314. This indicates that the handle has an active connection to the server
  2315. and that the dbd_db_disconnect function should be called before the
  2316. handle is destroyed.
  2317.  
  2318. Note that if you do need to fail, you should report errors via the drh
  2319. or imp_drh rather than via dbh or imp_dbh because imp_dbh will be
  2320. destroyed by the failure, so errors recorded in that handle will not be
  2321. visible to DBI, and hence not the user either.
  2322. Note to that the function is passed dbh and imp_dbh, and there is a
  2323. macro D_imp_drh_from_dbh which can recover the imp_drh from the imp_dbh,
  2324. but there is no DBI macro to provide you with the drh given either the
  2325. imp_dbh or the dbh or the imp_drh (and there's no way to recover the dbh
  2326. given just the imp_dbh).
  2327. This suggests that despite the notes about dbd_drv_error above taking an
  2328. SV *, it may be better to have two error routines, one taking imp_dbh
  2329. and one taking imp_drh instead.
  2330. With care, you can factor most of the formatting code out so that these
  2331. are small routines calling onto a common error formatter.
  2332. See the code in DBD::Informix 1.05.00 for more information.
  2333.  
  2334. The I<dbd_db_login6> function should return TRUE for success, FALSE otherwise.
  2335.  
  2336. Drivers implemented long ago may define the five-argument function
  2337. I<dbd_db_login> instead of I<dbd_db_login6>.
  2338. The missing argument is the attributes.
  2339. There are ways to work around the missing attributes, but they are
  2340. ungainly; it is much better to use the 6-argument form.
  2341.  
  2342. =cut
  2343.  
  2344. #=head3 The dbd_db_commit and dbd_db_rollback methods
  2345. #=POD-Perl-5.6.x=begin
  2346.  
  2347. =pod
  2348.  
  2349. =back
  2350.  
  2351. =over 2
  2352.  
  2353. =item The dbd_db_commit and dbd_db_rollback methods
  2354.  
  2355. =cut
  2356.  
  2357. #=POD-Perl-5.6.x=end
  2358.  
  2359. =pod
  2360.  
  2361.   int dbd_db_commit(SV *dbh, imp_dbh_t *imp_dbh);
  2362.   int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh);
  2363.  
  2364. These are used for commit and rollback. They should return TRUE for
  2365. success, FALSE for error.
  2366.  
  2367. The arguments I<dbh> and I<imp_dbh> are the same as for I<dbd_db_login6>
  2368. above; I will omit describing them in what follows, as they appear
  2369. always.
  2370.  
  2371. These functions should return TRUE for success, FALSE otherwise.
  2372.  
  2373. =cut
  2374.  
  2375. #=head3 The dbd_db_disconnect method
  2376. #=POD-Perl-5.6.x=begin
  2377.  
  2378. =pod
  2379.  
  2380. =back
  2381.  
  2382. =over 2
  2383.  
  2384. =item The dbd_db_disconnect method
  2385.  
  2386. =cut
  2387.  
  2388. #=POD-Perl-5.6.x=end
  2389.  
  2390. =pod
  2391.  
  2392. This is your private part of the I<disconnect> method. Any dbh with
  2393. the I<ACTIVE> flag on must be disconnected. (Note that you have to set
  2394. it in I<dbd_db_connect> above.)
  2395.  
  2396.   int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh);
  2397.  
  2398. The database handle will return TRUE for success, FALSE otherwise.
  2399. In any case it should do a:
  2400.  
  2401.   DBIc_ACTIVE_off(imp_dbh);
  2402.  
  2403. before returning so DBI knows that I<dbd_db_disconnect> was executed.
  2404.  
  2405. Note that there's nothing to stop a dbh being I<disconnected> while it
  2406. still have active children.
  2407. If your database API reacts badly to trying to use an sth in this
  2408. situation then you'll need to add code like this to all sth methods:
  2409.  
  2410.   if (!DBIc_ACTIVE(DBIc_PARENT_COM(imp_sth)))
  2411.     return 0;
  2412.  
  2413. Alternatively, you can add code to your driver to keep explicit track of
  2414. the statement handles that exist for each database handle and arrange to
  2415. destroy those handles before disconnecting from the database.
  2416. There is code to do this in DBD::Informix.
  2417. Similar comments apply to the driver handle keeping track of all the
  2418. database handles.
  2419. Note that the code which destroys the subordinate handles should only
  2420. release the associated database resources and mark the handles inactive;
  2421. it does not attempt to free the actual handle structures.
  2422.  
  2423. This function should return TRUE for success, FALSE otherwise, but
  2424. it is not clear what anything can do about a failure.
  2425.  
  2426. =cut
  2427.  
  2428. #=head3 The dbd_db_discon_all method
  2429. #=POD-Perl-5.6.x=begin
  2430.  
  2431. =pod
  2432.  
  2433. =back
  2434.  
  2435. =over 2
  2436.  
  2437. =item The dbd_db_discon_all method
  2438.  
  2439. =cut
  2440.  
  2441. #=POD-Perl-5.6.x=end
  2442.  
  2443. =pod
  2444.  
  2445.   int dbd_discon_all (SV *drh, imp_drh_t *imp_drh);
  2446.  
  2447. This function may be called at shutdown time. It should make
  2448. best-efforts to disconnect all database handles - if possible. Some
  2449. databases don't support that, in which case you can do nothing
  2450. but return 'success'.
  2451.  
  2452. This function should return TRUE for success, FALSE otherwise, but
  2453. it is not clear what anything can do about a failure.
  2454.  
  2455. =cut
  2456.  
  2457. #=head3 The dbd_db_destroy method
  2458. #=POD-Perl-5.6.x=begin
  2459.  
  2460. =pod
  2461.  
  2462. =back
  2463.  
  2464. =over 2
  2465.  
  2466. =item The dbd_db_destroy method
  2467.  
  2468. =cut
  2469.  
  2470. #=POD-Perl-5.6.x=end
  2471.  
  2472. =pod
  2473.  
  2474. This is your private part of the database handle destructor. Any dbh with
  2475. the I<IMPSET> flag on must be destroyed, so that you can safely free
  2476. resources. (Note that you have to set it in I<dbd_db_connect> above.)
  2477.  
  2478.   void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh)
  2479.   {
  2480.       DBIc_IMPSET_off(imp_dbh);
  2481.   }
  2482.  
  2483. The DBI Driver.xst code will have called dbd_db_disconnect for you,
  2484. if the handle is still 'active', before calling dbd_db_destroy.
  2485.  
  2486. Before returning the function must switch IMPSET to off, so DBI knows
  2487. that the destructor was called.
  2488.  
  2489. A DBI handle doesn't keep references to its children. But children
  2490. do keep references to their parents. So a database handle won't be
  2491. DESTROY'd until all its children have been DESTROY'd.
  2492.  
  2493. =cut
  2494.  
  2495. #=head3 The dbd_db_STORE_attrib method
  2496. #=POD-Perl-5.6.x=begin
  2497.  
  2498. =pod
  2499.  
  2500. =back
  2501.  
  2502. =over 2
  2503.  
  2504. =item The dbd_db_STORE_attrib method
  2505.  
  2506. =cut
  2507.  
  2508. #=POD-Perl-5.6.x=end
  2509.  
  2510. =pod
  2511.  
  2512. This function handles
  2513.  
  2514.   $dbh->{$key} = $value;
  2515.  
  2516. Its prototype is:
  2517.  
  2518.   int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv,
  2519.                           SV* valuesv);
  2520.  
  2521. You do not handle all attributes; on the contrary, you should not handle
  2522. DBI attributes here: leave this to DBI.
  2523. (There are two exceptions, I<AutoCommit> and I<ChopBlanks>, which you
  2524. should care about.)
  2525.  
  2526. The return value is TRUE if you have handled the attribute or FALSE
  2527. otherwise. If you are handling an attribute and something fails, you
  2528. should call I<dbd_drv_error>, so DBI can raise exceptions, if desired.
  2529. If I<dbd_drv_error> returns, however, you have a problem: the user will
  2530. never know about the error, because he typically will not check
  2531. C<$dbh-E<gt>errstr>.
  2532.  
  2533. I cannot recommend a general way of going on, if I<dbd_drv_error> returns,
  2534. but there are examples where even the DBI specification expects that
  2535. you croak(). (See the I<AutoCommit> method in L<DBI(3)>.)
  2536.  
  2537. If you have to store attributes, you should either use your private
  2538. data structure imp_xxx, the handle hash (via (HV*)SvRV(dbh)), or use
  2539. the private imp_data.
  2540.  
  2541. The first is best for internal C values like integers or pointers and
  2542. where speed is important within the driver. The handle hash is best for
  2543. values the user may want to get/set via driver-specific attributes.
  2544. The private imp_data is an additional SV attached to the handle. You
  2545. could think of it as an unnamed handle attribute. It's not normally used.
  2546.  
  2547. =cut
  2548.  
  2549. #=head3 The dbd_db_FETCH_attrib method
  2550. #=POD-Perl-5.6.x=begin
  2551.  
  2552. =pod
  2553.  
  2554. =back
  2555.  
  2556. =over 2
  2557.  
  2558. =item The dbd_db_FETCH_attrib method
  2559.  
  2560. =cut
  2561.  
  2562. #=POD-Perl-5.6.x=end
  2563.  
  2564. =pod
  2565.  
  2566. This is the counterpart of dbd_db_STORE_attrib, needed for:
  2567.  
  2568.   $value = $dbh->{$key};
  2569.  
  2570. Its prototype is:
  2571.  
  2572.   SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv);
  2573.  
  2574. Unlike all previous methods this returns an SV with the value. Note
  2575. that you should normally execute sv_2mortal, if you return a nonconstant
  2576. value. (Constant values are C<&sv_undef>, C<&sv_no> and C<&sv_yes>.)
  2577.  
  2578. Note, that DBI implements a caching algorithm for attribute values.
  2579. If you think, that an attribute may be fetched, you store it in the
  2580. dbh itself:
  2581.  
  2582.   if (cacheit) /* cache value for later DBI 'quick' fetch? */
  2583.       hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
  2584.  
  2585. =cut
  2586.  
  2587. #=head3 The dbd_st_prepare method
  2588. #=POD-Perl-5.6.x=begin
  2589.  
  2590. =pod
  2591.  
  2592. =back
  2593.  
  2594. =over 2
  2595.  
  2596. =item The dbd_st_prepare method
  2597.  
  2598. =cut
  2599.  
  2600. #=POD-Perl-5.6.x=end
  2601.  
  2602. =pod
  2603.  
  2604. This is the private part of the I<prepare> method. Note that you
  2605. B<must not> really execute the statement here. You may, for example,
  2606. preparse and validate the statement or do similar things.
  2607.  
  2608.   int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement,
  2609.                      SV* attribs);
  2610.  
  2611. A typical, simple, possibility is to do nothing and rely on the perl
  2612. perpare() code that set the Statement attribute on the handle. This
  2613. attribute can then be used by dbd_st_execute.
  2614.  
  2615. If the driver supports placeholders then the NUM_OF_PARAMS attribute
  2616. must be set correctly by dbd_st_prepare:
  2617.  
  2618.   DBIc_NUM_PARAMS(imp_sth) = ...
  2619.  
  2620. If you can, you should also setup attributes like NUM_OF_FIELDS,
  2621. NAME, ... here, but DBI doesn't require that. However, if you do,
  2622. document it.
  2623.  
  2624. In any case you should set the IMPSET flag, as you did in
  2625. I<dbd_db_connect> above:
  2626.  
  2627.   DBIc_IMPSET_on(imp_sth);
  2628.  
  2629. =cut
  2630.  
  2631. #=head3 The dbd_st_execute method
  2632. #=POD-Perl-5.6.x=begin
  2633.  
  2634. =pod
  2635.  
  2636. =back
  2637.  
  2638. =over 2
  2639.  
  2640. =item The dbd_st_execute method
  2641.  
  2642. =cut
  2643.  
  2644. #=POD-Perl-5.6.x=end
  2645.  
  2646. =pod
  2647.  
  2648. This is where a statement will really be executed.
  2649.  
  2650.   int dbd_st_execute(SV* sth, imp_sth_t* imp_sth);
  2651.  
  2652. Note, that you must be aware, that a statement may be executed
  2653. repeatedly.
  2654. Also, you should not expect, that I<finish> will be called between two
  2655. executions, so you'll might need code like the following near the start
  2656. of the function:
  2657.  
  2658.   if (DBIc_ACTIVE(imp_sth))
  2659.       dbd_st_finish(h, imp_sth);
  2660.  
  2661. If your driver supports the binding of parameters (it should!), but the
  2662. database doesn't, you must do it here. This can be done as follows:
  2663.  
  2664.   SV *svp;
  2665.   char* statement = DBD_ATTRIB_GET_PV(h, "Statement", 9, svp, "");
  2666.   int numParam = DBIc_NUM_PARAMS(imp_sth);
  2667.   int i;
  2668.  
  2669.   for (i = 0; i < numParam; i++)
  2670.   {
  2671.       char* value = dbd_db_get_param(sth, imp_sth, i);
  2672.       /* It is your drivers task to implement dbd_db_get_param,    */
  2673.       /* it must be setup as a counterpart of dbd_bind_ph.         */
  2674.       /* Look for '?' and replace it with 'value'.  Difficult      */
  2675.       /* task, note that you may have question marks inside        */
  2676.       /* quotes and comments the like ...  :-(                     */
  2677.       /* See DBD::mysql for an example. (Don't look too deep into  */
  2678.       /* the example, you will notice where I was lazy ...)        */
  2679.   }
  2680.  
  2681. The next thing is you really execute the statement.
  2682. Note that you must set the attributes NUM_OF_FIELDS,
  2683. NAME, etc when the statement is successfully executed if the driver has
  2684. not already done so.
  2685. They may be used even before a potential I<fetchrow>.
  2686. In particular you have to tell DBI the number of fields, that the
  2687. statement has, because it will be used by DBI internally.
  2688. Thus the function will typically ends with:
  2689.  
  2690.   if (isSelectStatement) {
  2691.       DBIc_NUM_FIELDS(imp_sth) = numFields;
  2692.       DBIc_ACTIVE_on(imp_sth);
  2693.   }
  2694.  
  2695. It is important that the ACTIVE flag only be set for C<SELECT> statements
  2696. (or any other statements that can return multiple sets of values from
  2697. the database using a cursor-like mechanism).
  2698. See I<dbd_db_connect> above for more explanations.
  2699.  
  2700. There plans for a preparse function to be provided by DBI, but this has
  2701. not reached fruition yet.
  2702. Meantime, if you want to know how ugly it can get, try looking at the
  2703. I<dbd_ix_preparse> in DBD::Informix I<dbdimp.ec> and the related
  2704. functions in I<iustoken.c> and I<sqltoken.c>.
  2705.  
  2706. =cut
  2707.  
  2708. #=head3 The dbd_st_fetch method
  2709. #=POD-Perl-5.6.x=begin
  2710.  
  2711. =pod
  2712.  
  2713. =back
  2714.  
  2715. =over 2
  2716.  
  2717. =item The dbd_st_fetch method
  2718.  
  2719. =cut
  2720.  
  2721. #=POD-Perl-5.6.x=end
  2722.  
  2723. =pod
  2724.  
  2725. This function fetches a row of data. The row is stored in in an array,
  2726. of SV's that DBI prepares for you. This has two advantages: it is fast
  2727. (you even reuse the SV's, so they don't have to be created after the
  2728. first fetchrow), and it guarantees that DBI handles I<bind_cols> for
  2729. you.
  2730.  
  2731. What you do is the following:
  2732.  
  2733.   AV* av;
  2734.   int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS
  2735.       is constant for this statement. There are drivers where this is
  2736.       not the case! */
  2737.   int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
  2738.   int i;
  2739.  
  2740.   if (!fetch_new_row_of_data(...)) {
  2741.       ... /* check for error or end-of-data */
  2742.       DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */
  2743.       return Nullav;
  2744.   }
  2745.   /* get the fbav (field buffer array value) for this row       */
  2746.   /* it is very important to only call this after you know      */
  2747.   /* that you have a row of data to return.                     */
  2748.   av = DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
  2749.   for (i = 0; i < numFields; i++) {
  2750.       SV* sv = fetch_a_field(..., i);
  2751.       if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) {
  2752.           /*  Remove white space from end (only) of sv  */
  2753.       }
  2754.       sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */
  2755.   }
  2756.   return av;
  2757.  
  2758. There's no need to use a fetch_a_field function returning an SV*.
  2759. It's more common to use your database API functions to fetch the
  2760. data as character strings and use code like this:
  2761.  
  2762.   sv_setpvn(AvARRAY(av)[i], char_ptr, char_count);
  2763.  
  2764. NULL values must be returned as undef. You can use code like this:
  2765.  
  2766.   SvOK_off(AvARRAY(av)[i]);
  2767.  
  2768. The function returns the AV prepared by DBI for success or C<Nullav>
  2769. otherwise.
  2770.  
  2771. =over 4
  2772.  
  2773. *FIX ME* Discuss what happens when there's no more data to fetch.
  2774. Are errors permitted if another fetch occurs after the first fetch
  2775. that reports no more data. (Permitted, not required.)
  2776.  
  2777. =back
  2778.  
  2779. If an error occurs which leaves the $sth in a state where remaining
  2780. rows can't be fetched then Active should be turned off before the
  2781. method returns.
  2782.  
  2783. =cut
  2784.  
  2785. #=head3 The dbd_st_finish3 method
  2786. #=POD-Perl-5.6.x=begin
  2787.  
  2788. =pod
  2789.  
  2790. =back
  2791.  
  2792. =over 2
  2793.  
  2794. =item The dbd_st_finish3 method
  2795.  
  2796. =cut
  2797.  
  2798. #=POD-Perl-5.6.x=end
  2799.  
  2800. =pod
  2801.  
  2802. The C<$sth-E<gt>finish> method can be called if the user wishes to
  2803. indicate that no more rows will be fetched even if the database has more
  2804. rows to offer, and the DBI code can call the function when handles are
  2805. being destroyed.
  2806. See the DBI specification for more background details.
  2807. In both circumstances, the DBI code ends up calling the
  2808. C<dbd_st_finish3> method (if you provide a mapping for I<dbd_st_finish3>
  2809. in I<dbdimp.h>), or I<dbd_st_finish> otherwise.
  2810. The difference is that dbd_st_finish3 takes a third argument which is an
  2811. C<int> with the value 1 if it is being called from a destroy method and
  2812. 0 otherwise.
  2813.  
  2814. Note that DBI v1.32 and earlier test on dbd_db_finish3 to call
  2815. dbd_st_finish3; if you provide dbd_st_finish3, either define
  2816. dbd_db_finish3 too, or insist on DBI v1.33 or later.
  2817.  
  2818. All it I<needs> to do is turn off the Active flag for the sth.
  2819. It will only be called by Driver.xst code, if the driver has set ACTIVE
  2820. to on for the sth.
  2821.  
  2822. Outline example:
  2823.  
  2824.   int dbd_st_finish3(SV* sth, imp_sth_t* imp_sth, int from_destroy) {
  2825.       if (DBIc_ACTIVE(imp_sth))
  2826.       {
  2827.           /* close cursor or equivalent action */
  2828.           DBIc_ACTIVE_off(imp_sth);
  2829.       }
  2830.       return 1;
  2831.   }
  2832.  
  2833. The from_destroy parameter is true if dbd_st_finish3 is being called
  2834. from DESTROY - and so the statement is about to be destroyed.
  2835. For many drivers there's no point in doing anything more than turing of
  2836. the Active flag in this case.
  2837.  
  2838. The function returns TRUE for success, FALSE otherwise, but there isn't
  2839. a lot anyone can do to recover if there is an error.
  2840.  
  2841. =cut
  2842.  
  2843. #=head3 The dbd_st_destroy method
  2844. #=POD-Perl-5.6.x=begin
  2845.  
  2846. =pod
  2847.  
  2848. =back
  2849.  
  2850. =over 2
  2851.  
  2852. =item The dbd_st_destroy method
  2853.  
  2854. =cut
  2855.  
  2856. #=POD-Perl-5.6.x=end
  2857.  
  2858. =pod
  2859.  
  2860. This function is the private part of the statement handle destructor.
  2861.  
  2862.   void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth) {
  2863.       ... /* any clean-up that's needed */
  2864.       DBIc_IMPSET_off(imp_sth); /* let DBI know we've done it   */
  2865.   }
  2866.  
  2867. The DBI Driver.xst code will call dbd_st_finish for you, if the sth has
  2868. the ACTIVE flag set, before calling dbd_st_destroy.
  2869.  
  2870. =cut
  2871.  
  2872. #=head3 The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
  2873. #=POD-Perl-5.6.x=begin
  2874.  
  2875. =pod
  2876.  
  2877. =back
  2878.  
  2879. =over 2
  2880.  
  2881. =item The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
  2882.  
  2883. =cut
  2884.  
  2885. #=POD-Perl-5.6.x=end
  2886.  
  2887. =pod
  2888.  
  2889. These functions correspond to dbd_db_STORE and dbd_db_FETCH attrib
  2890. above, except that they are for statement handles.
  2891. See above.
  2892.  
  2893.   int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv,
  2894.                           SV* valuesv);
  2895.   SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv);
  2896.  
  2897. =cut
  2898.  
  2899. #=head3 The dbd_bind_ph method
  2900. #=POD-Perl-5.6.x=begin
  2901.  
  2902. =pod
  2903.  
  2904. =back
  2905.  
  2906. =over 2
  2907.  
  2908. =item The dbd_bind_ph method
  2909.  
  2910. =cut
  2911.  
  2912. #=POD-Perl-5.6.x=end
  2913.  
  2914. =pod
  2915.  
  2916. This function is internally used by the I<bind_param> method, the
  2917. I<bind_param_inout> method and by the DBI Driver.xst code if C<execute>
  2918. is called with any bind parameters.
  2919.  
  2920.   int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param,
  2921.                    SV *value, IV sql_type, SV *attribs,
  2922.                    int is_inout, IV maxlen);
  2923.  
  2924. The I<param> argument holds an IV with the parameter number (1, 2, ...).
  2925. The I<value> argument is the parameter value and I<sql_type> is its type.
  2926.  
  2927. If your driver does not support bind_param_inout then you should
  2928. ignore I<maxlen> and croak if I<is_inout> is TRUE.
  2929.  
  2930. If your driver I<does> support bind_param_inout then you should
  2931. note that I<value> is the SV I<after> dereferencing the reference
  2932. passed to bind_param_inout.
  2933.  
  2934. In drivers of simple databases the function will, for example, store
  2935. the value in a parameter array and use it later in I<dbd_st_execute>.
  2936. See the I<DBD::mysql> driver for an example.
  2937.  
  2938. =cut
  2939.  
  2940. #=head3 Implementing bind_param_inout support
  2941. #=POD-Perl-5.6.x=begin
  2942.  
  2943. =pod
  2944.  
  2945. =back
  2946.  
  2947. =over 2
  2948.  
  2949. =item Implementing bind_param_inout support
  2950.  
  2951. =cut
  2952.  
  2953. #=POD-Perl-5.6.x=end
  2954.  
  2955. =pod
  2956.  
  2957. To provide support for parameters bound by reference rather than by
  2958. value, the driver must do a number of things.  First, and most
  2959. importantly, it must note the references and stash them in its own
  2960. driver structure.  Secondly, when a value is bound to a column, the
  2961. driver must discard any previous reference bound to the column.  On
  2962. each execute, the driver must evaluate the references and internally
  2963. bind the values resulting from the references.  This is only applicable
  2964. if the user writes:
  2965.  
  2966.   $sth->execute;
  2967.  
  2968. If the user writes:
  2969.  
  2970.   $sth->execute(@values);
  2971.  
  2972. then DBI automatically calls the binding code for each element of
  2973. @values.  These calls are indistinguishable from explicit user calls to
  2974. bind_param.
  2975.  
  2976. =cut
  2977.  
  2978. #=POD-Perl-5.6.x=begin
  2979.  
  2980. =pod
  2981.  
  2982. =back
  2983.  
  2984. =cut
  2985.  
  2986. #=POD-Perl-5.6.x=end
  2987.  
  2988. =pod
  2989.  
  2990. =head2 C/XS version of Makefile.PL
  2991.  
  2992. The I<Makefile.PL> file for a C/XS driver is similar to the code needed
  2993. for a pure Perl driver, but there are a number of extra bits of
  2994. information needed by the build system.
  2995. For example, the attributes list passed to C<WriteMakefile> needs to
  2996. specify the object files that need to be compiled and built into the
  2997. shared object (DLL).
  2998. This is often, but not necessarily, just dbdimp.o (unless that should be
  2999. dbdimp.obj because you're building on MS Windows).
  3000. Note that you can reliably determine the extension of the object files
  3001. from the $Config{obj_ext} values, and there are many other useful pieces
  3002. of configuration information lurking in that hash.
  3003. You get access to it with:
  3004.  
  3005.     use Config;
  3006.  
  3007. =head2 Methods which do not need to be written
  3008.  
  3009. The DBI code implements the majority of the methods which are
  3010. accessed using the notation DBI->function(), the only exceptions being
  3011. DBI->connect() and DBI->data_sources() which require support from the
  3012. driver.
  3013.  
  3014. The DBI code implements the following documented driver, database and
  3015. statement functions which do not need to be written by the DBD driver
  3016. writer.
  3017.  
  3018. =over 4
  3019.  
  3020. =item $dbh->do()
  3021.  
  3022. The default implementation of this function prepares, executes and
  3023. destroys the statement.  This can be replaced if there is a better
  3024. way to implement this, such as EXECUTE IMMEDIATE which can
  3025. sometimes be used if there are no parameters.
  3026.  
  3027. =item $h->errstr()
  3028.  
  3029. =item $h->err()
  3030.  
  3031. =item $h->state()
  3032.  
  3033. =item $h->trace()
  3034.  
  3035. The DBD driver does not need to worry about these routines at all.
  3036.  
  3037. =item $h->{ChopBlanks}
  3038.  
  3039. This attribute needs to be honured during fetch operations, but does
  3040. not need to be handled by the attribute handling code.
  3041.  
  3042. =item $h->{RaiseError}
  3043.  
  3044. The DBD driver does not need to worry about this attribute at all.
  3045.  
  3046. =item $h->{PrintError}
  3047.  
  3048. The DBD driver does not need to worry about this attribute at all.
  3049.  
  3050. =item $sth->bind_col()
  3051.  
  3052. Assuming the driver uses the DBIc_DBISTATE(imp_xxh)->get_fbav() function (C drivers,
  3053. see below), or the $sth->_set_fbav($data) method (Perl drivers)
  3054. the driver does not need to do anything about this routine.
  3055.  
  3056. =item $sth->bind_columns()
  3057.  
  3058. Regardless of whether the driver uses DBIc_DBISTATE(imp_xxh)->get_fbav(), the driver
  3059. does not need to do anything about this routine as it simply
  3060. iteratively calls $sth->bind_col().
  3061.  
  3062. =back
  3063.  
  3064. The DBI code implements a default implementation of the following
  3065. functions which do not need to be written by the DBD driver writer
  3066. unless the default implementation is incorrect for the Driver.
  3067.  
  3068. =over 4
  3069.  
  3070. =item $dbh->quote()
  3071.  
  3072. This should only be written if the database does not accept the ANSI
  3073. SQL standard for quoting strings, with the string enclosed in single
  3074. quotes and any embedded single quotes replaced by two consecutive
  3075. single quotes.
  3076.  
  3077. For the two argument form of quote, you need to implement the
  3078. C<type_info> method to provide the information that quote needs.
  3079.  
  3080. =item $dbh->ping()
  3081.  
  3082. This should be implemented as a simple efficient way to determine
  3083. whether the connection to the database is still alive. Typically
  3084. code like this:
  3085.  
  3086.   sub ping {
  3087.       my $dbh = shift;
  3088.       $sth = $dbh->prepare_cached(q{
  3089.           select * from A_TABLE_NAME where 1=0
  3090.       }) or return 0;
  3091.       $sth->execute or return 0;
  3092.       $sth->finish;
  3093.       return 1;
  3094.   }
  3095.  
  3096. where A_TABLE_NAME is the name of a table that always exists (such as a
  3097. database system catalogue).
  3098.  
  3099. =back
  3100.  
  3101. =head1 METADATA METHODS
  3102.  
  3103. The exposition above ignores the DBI MetaData methods.
  3104. The metadata methods are all associated with a database handle.
  3105.  
  3106. =head2 Using DBI::DBD::Metadata
  3107.  
  3108. The DBI::DBD::Metadata module is a good semi-automatic way for the developer of a DBD module to
  3109. write the get_info and type_info functions quickly and accurately.
  3110.  
  3111. =cut
  3112.  
  3113. #=head3 Generating the get_info method
  3114. #=POD-Perl-5.6.x=begin
  3115.  
  3116. =pod
  3117.  
  3118. =over 2
  3119.  
  3120. =item Generating the get_info method
  3121.  
  3122. =cut
  3123.  
  3124. #=POD-Perl-5.6.x=end
  3125.  
  3126. =pod
  3127.  
  3128. Prior to DBI v1.33, this existed as the method write_getinfo_pm in the
  3129. DBI::DBD module.
  3130. From DBI v1.33, it exists as the method write_getinfo_pm in the
  3131. DBI::DBD::Metadata module.
  3132. This discussion assumes you have DBI v1.33 or later.
  3133.  
  3134. You examine the documentation for write_getinfo_pm using:
  3135.  
  3136.     perldoc DBI::DBD::Metadata
  3137.  
  3138. To use it, you need a Perl DBI driver for your database which implements
  3139. the get_info method.
  3140. In practice, this means you need to install DBD::ODBC, an ODBC driver
  3141. manager, and an ODBC driver for your database.
  3142. With the pre-requisites in place, you might type:
  3143.  
  3144.     perl -MDBI::DBD::Metadata -e write_getinfo_pm \
  3145.             dbi:ODBC:foo_db username password Driver
  3146.  
  3147. The procedure writes to standard output the code that should be added to
  3148. your Driver.pm file and the code that should be written to
  3149. lib/DBD/Driver/GetInfo.pm.
  3150. You should review the output to ensure that it is sensible.
  3151.  
  3152. =cut
  3153.  
  3154. #=head3 Generating the type_info method
  3155. #=POD-Perl-5.6.x=begin
  3156.  
  3157. =pod
  3158.  
  3159. =back
  3160.  
  3161. =over 2
  3162.  
  3163. =item Generating the type_info method
  3164.  
  3165. =cut
  3166.  
  3167. #=POD-Perl-5.6.x=end
  3168.  
  3169. =pod
  3170.  
  3171. Given the idea of the write_getinfo_pm method, it was not hard to devise
  3172. a parallel method, write_typeinfo_pm, which does the analogous job for the
  3173. DBI type_info_all metadata method.
  3174. The the write_typeinfo_pm method was added to DBI v1.33.
  3175.  
  3176. You examine the documentation for write_typeinfo_pm using:
  3177.  
  3178.     perldoc DBI::DBD::Metadata
  3179.  
  3180. The setup is exactly analogous to the mechanism descibed in
  3181. L</Generating the get_info method>
  3182. With the pre-requisites in place, you might type:
  3183.  
  3184.     perl -MDBI::DBD::Metadata -e write_typeinfo \
  3185.             dbi:ODBC:foo_db username password Driver
  3186.  
  3187. The procedure writes to standard output the code that should be added to
  3188. your Driver.pm file and the code that should be written to
  3189. lib/DBD/Driver/TypeInfo.pm.
  3190. You should review the output to ensure that it is sensible.
  3191.  
  3192. =back
  3193.  
  3194. =head2 Writing DBD::Driver::db::get_info
  3195.  
  3196. If you use the DBI::DBD::Metadata module, then the code you need is
  3197. generated for you.
  3198.  
  3199. If you decide not to use the DBI::DBD::Metadata module, you should
  3200. probably borrow the code from a driver that has done so (eg
  3201. DBD::Informix from version 1.05 onwards) and crib the code from there,
  3202. or look at the code that generates that module and follow that.
  3203. The method in Driver.pm will be very simple; the method in
  3204. lib/DBD/Driver/GetInfo.pm is not very much more complex unless your DBMS itself is
  3205. much more complex.
  3206.  
  3207. Note that some of the DBI utility methods rely on information from the
  3208. get_info method to perform their operations correctly.
  3209. See, for example, the quote_identifier and quote methods, discussed
  3210. below.
  3211.  
  3212. =head2 Writing DBD::Driver::db::type_info_all
  3213.  
  3214. If you use the DBI::DBD::Metadata module, then the code you need is
  3215. generated for you.
  3216.  
  3217. If you decide not to use the DBI::DBD::Metadata module, you should
  3218. probably borrow the code from a driver that has done so (eg
  3219. DBD::Informix from version 1.05 onwards) and crib the code from there,
  3220. or look at the code that generates that module and follow that.
  3221. The method in Driver.pm will be very simple; the method in
  3222. lib/DBD/Driver/TypeInfo.pm is not very much more complex unless your DBMS
  3223. itself is much more complex.
  3224.  
  3225. =head2 Writing DBD::Driver::db::type_info
  3226.  
  3227. The guidelines on writing this method are still not really clear.
  3228. No sample implementation is available.
  3229.  
  3230. =head2 Writing DBD::Driver::db::table_info
  3231.  
  3232. =over 4
  3233.  
  3234. *FIX ME* The guidelines on writing this method have not been written yet.
  3235. No sample implementation is available.
  3236.  
  3237. =back
  3238.  
  3239. =head2 Writing DBD::Driver::db::column_info
  3240.  
  3241. =over 4
  3242.  
  3243. *FIX ME* The guidelines on writing this method have not been written yet.
  3244. No sample implementation is available.
  3245.  
  3246. =back
  3247.  
  3248. =head2 Writing DBD::Driver::db::primary_key_info
  3249.  
  3250. =over 4
  3251.  
  3252. *FIX ME* The guidelines on writing this method have not been written yet.
  3253. No sample implementation is available.
  3254.  
  3255. =back
  3256.  
  3257. =head2 Writing DBD::Driver::db::primary_key
  3258.  
  3259. =over 4
  3260.  
  3261. *FIX ME* The guidelines on writing this method have not been written yet.
  3262. No sample implementation is available.
  3263.  
  3264. =back
  3265.  
  3266. =head2 Writing DBD::Driver::db::foreign_key_info
  3267.  
  3268. =over 4
  3269.  
  3270. *FIX ME* The guidelines on writing this method have not been written yet.
  3271. No sample implementation is available.
  3272.  
  3273. =back
  3274.  
  3275. =head2 Writing DBD::Driver::db::tables
  3276.  
  3277. This method generates an array of names in a format suitable for being
  3278. embedded in SQL statements in places where a table name is expected.
  3279.  
  3280. If your database hews close enough to the SQL standard or if you have
  3281. implemented an appropriate table_info function and and the appropriate
  3282. quote_identifier function, then the DBI default version of this method
  3283. will work for your driver too.
  3284.  
  3285. Otherwise, you have to write a function yourself, such as:
  3286.  
  3287.     sub tables
  3288.     {
  3289.         my($dbh, $cat, $sch, $tab, $typ) = @_;
  3290.         my(@res);
  3291.         my($sth) = $dbh->table_info($cat, $sch, $tab, $typ);
  3292.         my(@arr);
  3293.         while (@arr = $sth->fetchrow_array)
  3294.         {
  3295.             push @res, $dbh->quote_identifier($arr[0], $arr[1], $arr[2]);
  3296.         }
  3297.         return @res;
  3298.     }
  3299.  
  3300. See also the default implementation in DBI.pm.
  3301.  
  3302. =head2 Writing DBD::Driver::db::quote
  3303.  
  3304. This method takes a value and converts it into a string suitable for
  3305. embedding in an SQL statement as a string literal.
  3306.  
  3307. If your DBMS accepts the SQL standard notation for strings (single
  3308. quotes around the string as a whole with any embedded single quotes
  3309. doubled up), then you do not need to write this method as DBI provides a
  3310. default method that does it for you.
  3311. If your DBMS uses an alternative notation or escape mechanism, then you
  3312. need to provide an equivalent function.
  3313. For example, suppose your DBMS used C notation with double quotes around
  3314. the string and backslashes escaping both double quotes and backslashes
  3315. themselves.
  3316. Then you might write the function as:
  3317.  
  3318.     sub quote
  3319.     {
  3320.         my($dbh, $str) = @_;
  3321.         $str =~ s/["\\]/\\$&/gmo;
  3322.         return qq{"$str"};
  3323.     }
  3324.  
  3325. Handling newlines and other control characters is left as an exercise
  3326. for the reader.
  3327.  
  3328. This sample method ignores the $data_type indicator which is the
  3329. optional second argument to the method.
  3330.  
  3331. =head2 Writing DBD::Driver::db::quote_identifier
  3332.  
  3333. This method is called to ensure that the name of the given table (or
  3334. other database object) can be embedded into an SQL statement without
  3335. danger of misinterpretation.
  3336. The result string should be usable in the text of an SQL statement as
  3337. the identifier for a table.
  3338.  
  3339. If your DBMS accepts the SQL standard notation for quoted identifiers
  3340. (which uses double quotes around the identifier as a whole, with any
  3341. embedded double quotes doubled up) and accepts "schema"."identifier"
  3342. (and "catalog"."schema"."identifier" when a catalog is specified), then
  3343. you do not need to write this method as DBI provides a default method
  3344. that does it for you.
  3345. In fact, even if your DBMS does not handle exactly that notation but you
  3346. have implemented the get_info method and it gives the correct responses,
  3347. then it will work for you.
  3348. If your database is fussier, then you need to implement your own version
  3349. of the function.
  3350.  
  3351. For example, DBD::Informix has to deal with an environment variable
  3352. DELIMIDENT.
  3353. If it is not set, then the DBMS treats names enclosed in double quotes
  3354. as strings rather than names, which is usually a syntax error.
  3355. Additionally, the catalog portion of the name is separated from the
  3356. schema and table by a different delimiter (colon instead of dot), and
  3357. the catalog portion is never enclosed in quotes.
  3358. (Fortunately, valid strings for the catalog will never contain weird
  3359. characters that might need to be escaped, unless you count dots, dashes,
  3360. slashes and at-signs as weird.)
  3361. Finally, an Informix database can contain objects that cannot be
  3362. accessed because they were created by a user with the DELIMIDENT
  3363. environment variable set, but the current user does not have it set.
  3364. By design choice, the quote_identifier method encloses those identifiers
  3365. in double quotes anyway, which generally triggers a syntax error, and
  3366. the metadata methods which generate lists of tables etc omit those
  3367. identifiers from the result sets.
  3368.  
  3369.     sub quote_identifier
  3370.     {
  3371.         my($dbh, $cat, $sch, $obj) = @_;
  3372.         my($rv) = "";
  3373.         my($qq) = (defined $ENV{DELIMIDENT}) ? '"' : '';
  3374.         $rv .= qq{$cat:} if (defined $cat);
  3375.         if (defined $sch)
  3376.         {
  3377.             if ($sch !~ m/^\w+$/o)
  3378.             {
  3379.                 $qq = '"';
  3380.                 $sch =~ s/$qq/$qq$qq/gm;
  3381.             }
  3382.             $rv .= qq{$qq$sch$qq.};
  3383.         }
  3384.         if (defined $obj)
  3385.         {
  3386.             if ($obj !~ m/^\w+$/o)
  3387.             {
  3388.                 $qq = '"';
  3389.                 $obj =~ s/$qq/$qq$qq/gm;
  3390.             }
  3391.             $rv .= qq{$qq$obj$qq};
  3392.         }
  3393.         return $rv;
  3394.     }
  3395.  
  3396. Handling newlines and other control characters is left as an exercise
  3397. for the reader.
  3398.  
  3399. Note that there is an optional fourth parameter to this function which
  3400. is a reference to a hash of attributes; this sample implementation
  3401. ignores that.
  3402. This sample implementation also ignores the single-argument variant of
  3403. the method.
  3404.  
  3405. =head1 WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE
  3406.  
  3407. Study Oraperl.pm (supplied with DBD::Oracle) and Ingperl.pm (supplied
  3408. with DBD::Ingres) and the corresponding dbdimp.c files for ideas.
  3409.  
  3410. Note that the emulation code sets $dbh->{CompatMode} = 1; for each
  3411. connection so that the internals of the driver can implement behaviour
  3412. compatible with the old interface when dealing with those handles.
  3413.  
  3414. =head2 Setting emulation perl variables
  3415.  
  3416. For example, ingperl has a $sql_rowcount variable. Rather than try
  3417. to manually update this in Ingperl.pm it can be done faster in C code.
  3418. In dbd_init():
  3419.  
  3420.   sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI);
  3421.  
  3422. In the relevant places do:
  3423.  
  3424.   if (DBIc_COMPAT(imp_sth))     /* only do this for compatibility mode handles */
  3425.       sv_setiv(sql_rowcount, the_row_count);
  3426.  
  3427. =head1 OTHER MISCELLANEOUS INFORMATION
  3428.  
  3429. =head2 The imp_xyz_t types
  3430.  
  3431. Any handle has a corresponding C structure filled with private data.
  3432. Some of this data is reserved for use by DBI (except for using the
  3433. DBIc macros below), some is for you. See the description of the
  3434. I<dbdimp.h> file above for examples. The most functions in dbdimp.c
  3435. are passed both the handle C<xyz> and a pointer to C<imp_xyz>. In
  3436. rare cases, however, you may use the following macros:
  3437.  
  3438. =over 2
  3439.  
  3440. =item D_imp_dbh(dbh)
  3441.  
  3442. Given a function argument I<dbh>, declare a variable I<imp_dbh> and
  3443. initialize it with a pointer to the handles private data. Note: This
  3444. must be a part of the function header, because it declares a variable.
  3445.  
  3446. =item D_imp_sth(sth)
  3447.  
  3448. Likewise for statement handles.
  3449.  
  3450. =item D_imp_xxx(h)
  3451.  
  3452. Given any handle, declare a variable I<imp_xxx> and initialize it
  3453. with a pointer to the handles private data. It is safe, for example,
  3454. to cast I<imp_xxx> to C<imp_dbh_t*>, if DBIc_TYPE(imp_xxx) == DBIt_DB.
  3455. (You can also call sv_derived_from(h, "DBI::db"), but that's much
  3456. slower.)
  3457.  
  3458. =item D_imp_dbh_from_sth
  3459.  
  3460. Given a imp_sth, declare a variable I<imp_dbh> and initialize it with a
  3461. pointer to the parent database handle's implementors structure.
  3462.  
  3463. =back
  3464.  
  3465. =head2 Using DBIc_IMPSET_on
  3466.  
  3467. The driver code which initializes a handle should use DBIc_IMPSET_on()
  3468. as soon as its state is such that the cleanup code must be called.
  3469. When this happens is determined by your driver code.
  3470.  
  3471. Failure to call this can lead to corruption of data structures.
  3472. For example, DBD::Informix maintains a linked list of database handles
  3473. in the driver, and within each handle, a linked list of statements.
  3474. Once a statement is added to the linked list, it is crucial that it is
  3475. cleaned up (removed from the list).
  3476. When DBIc_IMPSET_on() was being called too late, it was able to cause
  3477. all sorts of problems.
  3478.  
  3479. =head2 Using DBIc_is(), DBIc_has(), DBIc_on() and DBIc_off()
  3480.  
  3481. Once upon a long time ago, the only way of handling the internal DBI
  3482. boolean flags/attributes was through macros such as:
  3483.  
  3484.   DBIc_WARN       DBIc_WARN_on        DBIc_WARN_off
  3485.   DBIc_COMPAT     DBIc_COMPAT_on      DBIc_COMPAT_off
  3486.  
  3487. Each of these took an imp_xxh pointer as an argument.
  3488.  
  3489. Since then, new attributes have been added such as ChopBlanks,
  3490. RaiseError and PrintError, and these do not have the full set of
  3491. macros.
  3492. The approved method for handling these is now the four macros:
  3493.  
  3494.   DBIc_is(imp, flag)
  3495.   DBIc_has(imp, flag)       an alias for DBIc_is
  3496.   DBIc_on(imp, flag)
  3497.   DBIc_off(imp, flag)
  3498.   DBIc_set(imp, flag, on)   set if on is true, else clear
  3499.  
  3500. Consequently, the DBIc_XXXXX family of macros is now mostly deprecated
  3501. and new drivers should avoid using them, even though the older drivers
  3502. will probably continue to do so for quite a while yet. However...
  3503.  
  3504. There is an I<important exception> to that. The ACTIVE and IMPSET
  3505. flags should be set via the DBIc_ACTIVE_on and DBIc_IMPSET_on macros,
  3506. and unset via the DBIc_ACTIVE_off and DBIc_IMPSET_off macros.
  3507.  
  3508. =head2 Using the get_fbav() method
  3509.  
  3510. B<THIS IS CRITICAL> for C/XS drivers.
  3511.  
  3512. The $sth->bind_col() and $sth->bind_columns() documented in the DBI
  3513. specification do not have to be implemented by the driver writer because
  3514. DBI takes care of the details for you.
  3515. However, the key to ensuring that bound columns work is to call the
  3516. function DBIc_DBISTATE(imp_xxh)->get_fbav() in the code which fetches a
  3517. row of data.
  3518. This returns an AV, and each element of the AV contains the SV which
  3519. should be set to contain the returned data.
  3520.  
  3521. The pure Perl equivalent is the $sth->_set_fbav($data) method, as
  3522. described in the part on pure Perl drivers.
  3523.  
  3524. =head1 SUBCLASSING DBI DRIVERS
  3525.  
  3526. This is definitely an open subject. It can be done, as demonstrated by
  3527. the I<DBD::File> driver, but it is not as simple as one might think.
  3528.  
  3529. (Note that this topic is different from subclassing the DBI. For an
  3530. example of that, see the t/subclass.t file supplied with the DBI.)
  3531.  
  3532. The main problem is that the dbh's and sth's that your I<connect> and
  3533. I<prepare> methods return are not instances of your I<DBD::Driver::db>
  3534. or I<DBD::Driver::st> packages, they are not even derived from it.
  3535. Instead they are instances of the I<DBI::db> or I<DBI::st> classes or
  3536. a derived subclass. Thus, if you write a method I<mymethod> and do a
  3537.  
  3538.   $dbh->mymethod()
  3539.  
  3540. then the autoloader will search for that method in the package I<DBI::db>.
  3541. Of course you can instead to a
  3542.  
  3543.   $dbh->func('mymethod')
  3544.  
  3545. and that will indeed work, even if I<mymethod> is inherited, but not
  3546. without additional work. Setting C<@ISA> is not sufficient.
  3547.  
  3548. =head2 Overwriting methods
  3549.  
  3550. The first problem is, that the I<connect> method has no idea of
  3551. subclasses. For example, you cannot implement base class and subclass
  3552. in the same file: The I<install_driver> method wants to do a
  3553.  
  3554.   require DBD::Driver;
  3555.  
  3556. In particular, your subclass B<has> to be a separate driver, from
  3557. the view of DBI, and you cannot share driver handles.
  3558.  
  3559. Of course that's not much of a problem. You should even be able
  3560. to inherit the base classes I<connect> method. But you cannot
  3561. simply overwrite the method, unless you do something like this,
  3562. quoted from I<DBD::CSV>:
  3563.  
  3564.   sub connect ($$;$$$) {
  3565.       my ($drh, $dbname, $user, $auth, $attr) = @_;
  3566.  
  3567.       my $this = $drh->DBD::File::dr::connect($dbname, $user, $auth, $attr);
  3568.       if (!exists($this->{csv_tables})) {
  3569.           $this->{csv_tables} = {};
  3570.       }
  3571.  
  3572.       $this;
  3573.   }
  3574.  
  3575. Note that we cannot do a
  3576.  
  3577.   $srh->SUPER::connect($dbname, $user, $auth, $attr);
  3578.  
  3579. as we would usually do in a an OO environment, because $drh is an instance
  3580. of I<DBI::dr>. And note, that the I<connect> method of I<DBD::File> is
  3581. able to handle subclass attributes. See the description of Pure Perl
  3582. drivers above.
  3583.  
  3584. It is essential that you always call superclass method in the above
  3585. manner. However, that should do.
  3586.  
  3587. =head2 Attribute handling
  3588.  
  3589. Fortunately the DBI specifications allow a simple, but still performant way of
  3590. handling attributes. The idea is based on the convention that any
  3591. driver uses a prefix I<driver_> for its private methods. Thus it's
  3592. always clear whether to pass attributes to the super class or not.
  3593. For example, consider this STORE method from the I<DBD::CSV> class:
  3594.  
  3595.   sub STORE {
  3596.       my ($dbh, $attr, $val) = @_;
  3597.       if ($attr !~ /^driver_/) {
  3598.           return $dbh->DBD::File::db::STORE($attr, $val);
  3599.       }
  3600.       if ($attr eq 'driver_foo') {
  3601.       ...
  3602.   }
  3603.  
  3604. =cut
  3605.  
  3606. use Exporter ();
  3607. use Config qw(%Config);
  3608. use Carp;
  3609. use Cwd;
  3610. use strict;
  3611. use vars qw(
  3612.     @ISA @EXPORT
  3613.     $is_dbi
  3614. );
  3615.  
  3616. BEGIN { if ($^O eq 'VMS') {
  3617.     require vmsish;
  3618.     import  vmsish;
  3619.     require VMS::Filespec;
  3620.     import  VMS::Filespec;
  3621. }}
  3622.  
  3623. @ISA = qw(Exporter);
  3624.  
  3625. @EXPORT = qw(
  3626.     dbd_dbi_dir
  3627.     dbd_dbi_arch_dir
  3628.     dbd_edit_mm_attribs
  3629.     dbd_postamble
  3630. );
  3631.  
  3632. BEGIN {
  3633.     $is_dbi = (-r 'DBI.pm' && -r 'DBI.xs' && -r 'DBIXS.h');
  3634.     require DBI unless $is_dbi;
  3635. }
  3636.  
  3637. my $done_inst_checks;
  3638.  
  3639. sub _inst_checks {
  3640.     return if $done_inst_checks++;
  3641.     my $cwd = cwd();
  3642.     if ($cwd =~ /$Config{path_sep}/) {
  3643.     warn "*** Warning: Path separator characters (`$Config{path_sep}') ",
  3644.         "in the current directory path ($cwd) may cause problems\a\n\n";
  3645.         sleep 2;
  3646.     }
  3647.     if ($cwd =~ /\s/) {
  3648.     warn "*** Warning: whitespace characters ",
  3649.         "in the current directory path ($cwd) may cause problems\a\n\n";
  3650.         sleep 2;
  3651.     }
  3652.     if (   $^O eq 'MSWin32'
  3653.     && $Config{cc} eq 'cl'
  3654.     && !(exists $ENV{'LIB'} && exists $ENV{'INCLUDE'}))
  3655.     {
  3656.     print <<EOT;
  3657. *** You're using Microsoft Visual C++ compiler but the LIB and INCLUDE environment
  3658.     variables are not both set. If you have 'unresolved external symbol'
  3659.     errors during linking, run the vcvars32.bat batch file to set up your
  3660.     LIB and INCLUDE environment variables, and try again.
  3661.     A copy of vcvars32.bat can typically be found in the following
  3662.     directories under your Visual Studio install directory:
  3663.         Visual C++ 6.0:     vc98\\bin
  3664.         Visual Studio .NET: vc7\\bin
  3665.  
  3666. EOT
  3667.     sleep 2;
  3668.     }
  3669. }
  3670.  
  3671. sub dbd_edit_mm_attribs {
  3672.     # this both edits the attribs in-place and returns the flattened attribs
  3673.     my $mm_attr = shift;
  3674.     my $dbd_attr = shift || {};
  3675.     croak "dbd_edit_mm_attribs( \%makemaker [, \%other ]): too many parameters"
  3676.     if @_;
  3677.     _inst_checks();
  3678.  
  3679.     # decide what needs doing
  3680.  
  3681.     # do whatever needs doing
  3682.     if ($dbd_attr->{create_pp_tests}) {
  3683.     # XXX need to convert this to work within the generated Makefile
  3684.     # so 'make' creates them and 'make clean' deletes them
  3685.     my %test_variants = (
  3686.         pp => {    name => "DBI::PurePerl",
  3687.             add => [ '$ENV{DBI_PUREPERL}=2;' ],
  3688.         },
  3689.         mx => {    name => "DBD::Multiplex",
  3690.             add => [ q{$ENV{DBI_AUTOPROXY}='dbi:Multiplex:';} ],
  3691.         }
  3692.     #   px => {    name => "DBD::Proxy",
  3693.     #        need mechanism for starting/stopping the proxy server
  3694.     #        add => [ q{$ENV{DBI_AUTOPROXY}='dbi:Proxy:XXX';} ],
  3695.     #   }
  3696.     );
  3697.     # currently many tests fail - DBD::Multiplex needs more work
  3698.     # to bring it up to date and improve transparency.
  3699.     delete $test_variants{mx}; # unless -f "lib/DBD/Multiplex.pm";
  3700.  
  3701.     opendir DIR, 't' or die "Can't create variants of tests in 't' directory: $!";
  3702.     my @tests = grep { /\.t$/ } readdir DIR;
  3703.     closedir DIR;
  3704.  
  3705.     # XXX one day we may try combinations here, ie pp+mx!
  3706.  
  3707.     foreach my $test (sort @tests) {
  3708.         next if $test !~ /^[0-8]/;
  3709.         my $usethr = ($test =~ /(\d+|\b)thr/ && $] >= 5.008 && $Config{useithreads});
  3710.  
  3711.         while ( my ($v_type, $v_info) = each %test_variants ) {
  3712.         my $v_test = "t/zv${v_type}_$test";
  3713.         printf "Creating %-16s test variant: $v_test %s\n",
  3714.             $v_info->{name}, ($usethr) ? "(use threads)" : "";
  3715.         open PPT, ">$v_test" or warn "Can't create $v_test: $!";
  3716.         print PPT "#!perl -w\n";
  3717.         print PPT "use threads;\n" if $usethr;
  3718.         print PPT "$_\n" foreach @{$v_info->{add}};
  3719.         print PPT "do 't/$test' or warn \$!;\n";
  3720.         print PPT 'die if $@;'."\n";
  3721.         print PPT "exit 0\n";
  3722.         close PPT or warn "Error writing $v_test: $!";
  3723.         }
  3724.     }
  3725.     }
  3726.     return %$mm_attr;
  3727. }
  3728.  
  3729. sub dbd_dbi_dir {
  3730.     _inst_checks();
  3731.     return '.' if $is_dbi;
  3732.     my $dbidir = $INC{'DBI.pm'} || die "DBI.pm not in %INC!";
  3733.     $dbidir =~ s:/DBI\.pm$::;
  3734.     return $dbidir;
  3735. }
  3736.  
  3737. sub dbd_dbi_arch_dir {
  3738.     _inst_checks();
  3739.     return '$(INST_ARCHAUTODIR)' if $is_dbi;
  3740.     my $dbidir = dbd_dbi_dir();
  3741.     my @try = map { "$_/auto/DBI" } @INC;
  3742.     my @xst = grep { -f "$_/Driver.xst" } @try;
  3743.     Carp::croak("Unable to locate Driver.xst in @try") unless @xst;
  3744.     Carp::carp( "Multiple copies of Driver.xst found in: @xst") if @xst > 1;
  3745.     print "Using DBI $DBI::VERSION (for perl $] on $Config{archname}) installed in $xst[0]\n";
  3746.     return $xst[0];
  3747. }
  3748.  
  3749. sub dbd_postamble {
  3750.     my $self = shift;
  3751.     _inst_checks();
  3752.     my $dbi_instarch_dir = ($is_dbi) ? "." : dbd_dbi_arch_dir();
  3753.     my $dbi_driver_xst= '$(DBI_INSTARCH_DIR)/Driver.xst';
  3754.     my $xstf_h = '$(DBI_INSTARCH_DIR)/Driver_xst.h';
  3755.     if ($^O eq 'VMS') {
  3756.     $dbi_instarch_dir = vmsify($dbi_instarch_dir.'/') unless $is_dbi;
  3757.     $dbi_driver_xst= '$(DBI_INSTARCH_DIR)Driver.xst';
  3758.     $xstf_h = '$(DBI_INSTARCH_DIR)Driver_xst.h';
  3759.     }
  3760.  
  3761.     # we must be careful of quotes, expecially for Win32 here.
  3762.     return '
  3763. # --- This section was generated by DBI::DBD::dbd_postamble()
  3764. DBI_INSTARCH_DIR='.$dbi_instarch_dir.'
  3765. DBI_DRIVER_XST='.$dbi_driver_xst.'
  3766.  
  3767. # The main dependancy (technically correct but probably not used)
  3768. $(BASEEXT).c: $(BASEEXT).xsi
  3769.  
  3770. # This dependancy is needed since MakeMaker uses the .xs.o rule
  3771. $(BASEEXT)$(OBJ_EXT): $(BASEEXT).xsi
  3772.  
  3773. $(BASEEXT).xsi: $(DBI_DRIVER_XST) '.$xstf_h.'
  3774.     $(PERL) -p -e "s/~DRIVER~/$(BASEEXT)/g" $(DBI_DRIVER_XST) > $(BASEEXT).xsi
  3775.  
  3776. # ---
  3777. ';
  3778. }
  3779.  
  3780. package DBDI; # just to reserve it via PAUSE for the future
  3781.  
  3782. 1;
  3783.  
  3784. __END__
  3785.  
  3786. =head1 AUTHORS
  3787.  
  3788. Jonathan Leffler <jleffler@us.ibm.com> (previously <jleffler@informix.com>),
  3789. Jochen Wiedmann <joe@ispsoft.de>,
  3790. Steffen Goeldner <sgoeldner@cpan.org>,
  3791. and Tim Bunce <dbi-users@perl.org>.
  3792.  
  3793. =cut
  3794.