1DBI::DBD(3)           User Contributed Perl Documentation          DBI::DBD(3)
2
3
4

NAME

6       DBI::DBD - Perl DBI Database Driver Writer's Guide
7

SYNOPSIS

9         perldoc DBI::DBD
10
11   Version and volatility
12       This document is still a minimal draft which is in need of further
13       work.
14
15       The changes will occur both because the DBI specification is changing
16       and hence the requirements on DBD drivers change, and because feedback
17       from people reading this document will suggest improvements to it.
18
19       Please read the DBI documentation first and fully, including the DBI
20       FAQ.  Then reread the DBI specification again as you're reading this.
21       It'll help.
22
23       This document is a patchwork of contributions from various authors.
24       More contributions (preferably as patches) are very welcome.
25

DESCRIPTION

27       This document is primarily intended to help people writing new database
28       drivers for the Perl Database Interface (Perl DBI).  It may also help
29       others interested in discovering why the internals of a DBD driver are
30       written the way they are.
31
32       This is a guide.  Few (if any) of the statements in it are completely
33       authoritative under all possible circumstances.  This means you will
34       need to use judgement in applying the guidelines in this document.  If
35       in any doubt at all, please do contact the dbi-dev mailing list
36       (details given below) where Tim Bunce and other driver authors can
37       help.
38

CREATING A NEW DRIVER

40       The first rule for creating a new database driver for the Perl DBI is
41       very simple: DON'T!
42
43       There is usually a driver already available for the database you want
44       to use, almost regardless of which database you choose. Very often, the
45       database will provide an ODBC driver interface, so you can often use
46       DBD::ODBC to access the database. This is typically less convenient on
47       a Unix box than on a Microsoft Windows box, but there are numerous
48       options for ODBC driver managers on Unix too, and very often the ODBC
49       driver is provided by the database supplier.
50
51       Before deciding that you need to write a driver, do your homework to
52       ensure that you are not wasting your energies.
53
54       [As of December 2002, the consensus is that if you need an ODBC driver
55       manager on Unix, then the unixODBC driver (available from
56       <http://www.unixodbc.org/>) is the way to go.]
57
58       The second rule for creating a new database driver for the Perl DBI is
59       also very simple: Don't -- get someone else to do it for you!
60
61       Nevertheless, there are occasions when it is necessary to write a new
62       driver, often to use a proprietary language or API to access the
63       database more swiftly, or more comprehensively, than an ODBC driver
64       can.  Then you should read this document very carefully, but with a
65       suitably sceptical eye.
66
67       If there is something in here that does not make any sense, question
68       it.  You might be right that the information is bogus, but don't come
69       to that conclusion too quickly.
70
71   URLs and mailing lists
72       The primary web-site for locating DBI software and information is
73
74         http://dbi.perl.org/
75
76       There are two main and one auxiliary mailing lists for people working
77       with DBI.  The primary lists are dbi-users@perl.org for general users
78       of DBI and DBD drivers, and dbi-dev@perl.org mainly for DBD driver
79       writers (don't join the dbi-dev list unless you have a good reason).
80       The auxiliary list is dbi-announce@perl.org for announcing new releases
81       of DBI or DBD drivers.
82
83       You can join these lists by accessing the web-site
84       <http://dbi.perl.org/>.  The lists are closed so you cannot send email
85       to any of the lists unless you join the list first.
86
87       You should also consider monitoring the comp.lang.perl.* newsgroups,
88       especially comp.lang.perl.modules.
89
90   The Cheetah book
91       The definitive book on Perl DBI is the Cheetah book, so called because
92       of the picture on the cover. Its proper title is 'Programming the Perl
93       DBI: Database programming with Perl' by Alligator Descartes and Tim
94       Bunce, published by O'Reilly Associates, February 2000, ISBN
95       1-56592-699-4. Buy it now if you have not already done so, and read it.
96
97   Locating drivers
98       Before writing a new driver, it is in your interests to find out
99       whether there already is a driver for your database.  If there is such
100       a driver, it would be much easier to make use of it than to write your
101       own!
102
103       The primary web-site for locating Perl software is
104       <http://search.cpan.org/>.  You should look under the various modules
105       listings for the software you are after. For example:
106
107         http://search.cpan.org/modlist/Database_Interfaces
108
109       Follow the DBD:: and DBIx:: links at the top to see those subsets.
110
111       See the DBI docs for information on DBI web sites and mailing lists.
112
113   Registering a new driver
114       Before going through any official registration process, you will need
115       to establish that there is no driver already in the works. You'll do
116       that by asking the DBI mailing lists whether there is such a driver
117       available, or whether anybody is working on one.
118
119       When you get the go ahead, you will need to establish the name of the
120       driver and a prefix for the driver. Typically, the name is based on the
121       name of the database software it uses, and the prefix is a contraction
122       of that. Hence, DBD::Oracle has the name Oracle and the prefix 'ora_'.
123       The prefix must be lowercase and contain no underscores other than the
124       one at the end.
125
126       This information will be recorded in the DBI module. Apart from
127       documentation purposes, registration is a prerequisite for installing
128       private methods.
129
130       If you are writing a driver which will not be distributed on CPAN, then
131       you should choose a prefix beginning with 'x_', to avoid potential
132       prefix collisions with drivers registered in the future. Thus, if you
133       wrote a non-CPAN distributed driver called DBD::CustomDB, the prefix
134       might be 'x_cdb_'.
135
136       This document assumes you are writing a driver called DBD::Driver, and
137       that the prefix 'drv_' is assigned to the driver.
138
139   Two styles of database driver
140       There are two distinct styles of database driver that can be written to
141       work with the Perl DBI.
142
143       Your driver can be written in pure Perl, requiring no C compiler.  When
144       feasible, this is the best solution, but most databases are not written
145       in such a way that this can be done. Some examples of pure Perl drivers
146       are DBD::File and DBD::CSV.
147
148       Alternatively, and most commonly, your driver will need to use some C
149       code to gain access to the database. This will be classified as a C/XS
150       driver.
151
152   What code will you write?
153       There are a number of files that need to be written for either a pure
154       Perl driver or a C/XS driver. There are no extra files needed only by a
155       pure Perl driver, but there are several extra files needed only by a
156       C/XS driver.
157
158       Files common to pure Perl and C/XS drivers
159
160       Assuming that your driver is called DBD::Driver, these files are:
161
162       ·   Makefile.PL
163
164       ·   META.yml
165
166       ·   README
167
168       ·   MANIFEST
169
170       ·   Driver.pm
171
172       ·   lib/Bundle/DBD/Driver.pm
173
174       ·   lib/DBD/Driver/Summary.pm
175
176       ·   t/*.t
177
178       The first four files are mandatory. Makefile.PL is used to control how
179       the driver is built and installed. The README file tells people who
180       download the file about how to build the module and any prerequisite
181       software that must be installed. The MANIFEST file is used by the
182       standard Perl module distribution mechanism. It lists all the source
183       files that need to be distributed with your module. Driver.pm is what
184       is loaded by the DBI code; it contains the methods peculiar to your
185       driver.
186
187       Although the META.yml file is not required you are advised to create
188       one. Of particular importance are the build_requires and
189       configure_requires attributes which newer CPAN modules understand.  You
190       use these to tell the CPAN module (and CPANPLUS) that your build and
191       configure mechanisms require DBI. The best reference for META.yml (at
192       the time of writing) is
193       http://module-build.sourceforge.net/META-spec-v1.4.html <http://module-
194       build.sourceforge.net/META-spec-v1.4.html>. You can find a reasonable
195       example of a META.yml in DBD::ODBC.
196
197       The lib/Bundle/DBD/Driver.pm file allows you to specify other Perl
198       modules on which yours depends in a format that allows someone to type
199       a simple command and ensure that all the pre-requisites are in place as
200       well as building your driver.
201
202       The lib/DBD/Driver/Summary.pm file contains (an updated version of) the
203       information that was included - or that would have been included - in
204       the appendices of the Cheetah book as a summary of the abilities of
205       your driver and the associated database.
206
207       The files in the t subdirectory are unit tests for your driver.  You
208       should write your tests as stringently as possible, while taking into
209       account the diversity of installations that you can encounter:
210
211       ·   Your tests should not casually modify operational databases.
212
213       ·   You should never damage existing tables in a database.
214
215       ·   You should code your tests to use a constrained name space within
216           the database. For example, the tables (and all other named objects)
217           that are created could all begin with 'dbd_drv_'.
218
219       ·   At the end of a test run, there should be no testing objects left
220           behind in the database.
221
222       ·   If you create any databases, you should remove them.
223
224       ·   If your database supports temporary tables that are automatically
225           removed at the end of a session, then exploit them as often as
226           possible.
227
228       ·   Try to make your tests independent of each other. If you have a
229           test t/t11dowhat.t that depends upon the successful running of
230           t/t10thingamy.t, people cannot run the single test case
231           t/t11dowhat.t. Further, running t/t11dowhat.t twice in a row is
232           likely to fail (at least, if t/t11dowhat.t modifies the database at
233           all) because the database at the start of the second run is not
234           what you saw at the start of the first run.
235
236       ·   Document in your README file what you do, and what privileges
237           people need to do it.
238
239       ·   You can, and probably should, sequence your tests by including a
240           test number before an abbreviated version of the test name; the
241           tests are run in the order in which the names are expanded by
242           shell-style globbing.
243
244       ·   It is in your interests to ensure that your tests work as widely as
245           possible.
246
247       Many drivers also install sub-modules DBD::Driver::SubModule for any of
248       a variety of different reasons, such as to support the metadata methods
249       (see the discussion of "METADATA METHODS" below). Such sub-modules are
250       conventionally stored in the directory lib/DBD/Driver. The module
251       itself would usually be in a file SubModule.pm. All such sub-modules
252       should themselves be version stamped (see the discussions far below).
253
254       Extra files needed by C/XS drivers
255
256       The software for a C/XS driver will typically contain at least four
257       extra files that are not relevant to a pure Perl driver.
258
259       ·   Driver.xs
260
261       ·   Driver.h
262
263       ·   dbdimp.h
264
265       ·   dbdimp.c
266
267       The Driver.xs file is used to generate C code that Perl can call to
268       gain access to the C functions you write that will, in turn, call down
269       onto your database software.
270
271       The Driver.h header is a stylized header that ensures you can access
272       the necessary Perl and DBI macros, types, and function declarations.
273
274       The dbdimp.h is used to specify which functions have been implemented
275       by your driver.
276
277       The dbdimp.c file is where you write the C code that does the real work
278       of translating between Perl-ish data types and what the database
279       expects to use and return.
280
281       There are some (mainly small, but very important) differences between
282       the contents of Makefile.PL and Driver.pm for pure Perl and C/XS
283       drivers, so those files are described both in the section on creating a
284       pure Perl driver and in the section on creating a C/XS driver.
285
286       Obviously, you can add extra source code files to the list.
287
288   Requirements on a driver and driver writer
289       To be remotely useful, your driver must be implemented in a format that
290       allows it to be distributed via CPAN, the Comprehensive Perl Archive
291       Network (<http://www.cpan.org/> and <http://search.cpan.org>).  Of
292       course, it is easier if you do not have to meet this criterion, but you
293       will not be able to ask for much help if you do not do so, and no-one
294       is likely to want to install your module if they have to learn a new
295       installation mechanism.
296

CREATING A PURE PERL DRIVER

298       Writing a pure Perl driver is surprisingly simple. However, there are
299       some problems you should be aware of. The best option is of course
300       picking up an existing driver and carefully modifying one method after
301       the other.
302
303       Also look carefully at DBD::AnyData and DBD::Template.
304
305       As an example we take a look at the DBD::File driver, a driver for
306       accessing plain files as tables, which is part of the DBD::CSV package.
307
308       The minimal set of files we have to implement are Makefile.PL, README,
309       MANIFEST and Driver.pm.
310
311   Pure Perl version of Makefile.PL
312       You typically start with writing Makefile.PL, a Makefile generator. The
313       contents of this file are described in detail in the
314       ExtUtils::MakeMaker man pages. It is definitely a good idea if you
315       start reading them. At least you should know about the variables
316       CONFIGURE, DEFINED, PM, DIR, EXE_FILES, INC, LIBS, LINKTYPE, NAME,
317       OPTIMIZE, PL_FILES, VERSION, VERSION_FROM, clean, depend, realclean
318       from the ExtUtils::MakeMaker man page: these are used in almost any
319       Makefile.PL.
320
321       Additionally read the section on Overriding MakeMaker Methods and the
322       descriptions of the distcheck, disttest and dist targets: They will
323       definitely be useful for you.
324
325       Of special importance for DBI drivers is the postamble method from the
326       ExtUtils::MM_Unix man page.
327
328       For Emacs users, I recommend the libscan method, which removes Emacs
329       backup files (file names which end with a tilde '~') from lists of
330       files.
331
332       Now an example, I use the word "Driver" wherever you should insert your
333       driver's name:
334
335         # -*- perl -*-
336
337         use ExtUtils::MakeMaker;
338
339         WriteMakefile(
340             dbd_edit_mm_attribs( {
341                 'NAME'         => 'DBD::Driver',
342                 'VERSION_FROM' => 'Driver.pm',
343                 'INC'          => '',
344                 'dist'         => { 'SUFFIX'   => '.gz',
345                                     'COMPRESS' => 'gzip -9f' },
346                 'realclean'    => { FILES => '*.xsi' },
347                 'PREREQ_PM'    => '1.03',
348                 'CONFIGURE'    => sub {
349                     eval {require DBI::DBD;};
350                     if ($@) {
351                         warn $@;
352                         exit 0;
353                     }
354                     my $dbi_arch_dir = dbd_dbi_arch_dir();
355                     if (exists($opts{INC})) {
356                         return {INC => "$opts{INC} -I$dbi_arch_dir"};
357                     } else {
358                         return {INC => "-I$dbi_arch_dir"};
359                     }
360                 }
361             },
362             { create_pp_tests => 1})
363         );
364
365         package MY;
366         sub postamble { return main::dbd_postamble(@_); }
367         sub libscan {
368             my ($self, $path) = @_;
369             ($path =~ m/\~$/) ? undef : $path;
370         }
371
372       Note the calls to "dbd_edit_mm_attribs()" and "dbd_postamble()".
373
374       The second hash reference in the call to "dbd_edit_mm_attribs()"
375       (containing "create_pp_tests()") is optional; you should not use it
376       unless your driver is a pure Perl driver (that is, it does not use C
377       and XS code). Therefore, the call to "dbd_edit_mm_attribs()" is not
378       relevant for C/XS drivers and may be omitted; simply use the (single)
379       hash reference containing NAME etc as the only argument to
380       "WriteMakefile()".
381
382       Note that the "dbd_edit_mm_attribs()" code will fail if you do not have
383       a t sub-directory containing at least one test case.
384
385       PREREQ_PM tells MakeMaker that DBI (version 1.03 in this case) is
386       required for this module. This will issue a warning that DBI 1.03 is
387       missing if someone attempts to install your DBD without DBI 1.03. See
388       CONFIGURE below for why this does not work reliably in stopping cpan
389       testers failing your module if DBI is not installed.
390
391       CONFIGURE is a subroutine called by MakeMaker during "WriteMakefile".
392       By putting the "require DBI::DBD" in this section we can attempt to
393       load DBI::DBD but if it is missing we exit with success. As we exit
394       successfully without creating a Makefile when DBI::DBD is missing cpan
395       testers will not report a failure. This may seem at odds with PREREQ_PM
396       but PREREQ_PM does not cause "WriteMakefile" to fail (unless you also
397       specify PREREQ_FATAL which is strongly discouraged by MakeMaker) so
398       "WriteMakefile" would continue to call "dbd_dbi_arch_dir" and fail.
399
400       All drivers must use "dbd_postamble()" or risk running into problems.
401
402       Note the specification of VERSION_FROM; the named file (Driver.pm) will
403       be scanned for the first line that looks like an assignment to
404       $VERSION, and the subsequent text will be used to determine the version
405       number.  Note the commentary in ExtUtils::MakeMaker on the subject of
406       correctly formatted version numbers.
407
408       If your driver depends upon external software (it usually will), you
409       will need to add code to ensure that your environment is workable
410       before the call to "WriteMakefile()". If you need to check for the
411       existence of an external library and perhaps modify INC to include the
412       paths to where the external library header files are located and you
413       cannot find the library or header files make sure you output a message
414       saying they cannot be found but "exit 0" (success) before calling
415       "WriteMakefile" or CPAN testers will fail your module if the external
416       library is not found.
417
418       A full-fledged Makefile.PL can be quite large (for example, the files
419       for DBD::Oracle and DBD::Informix are both over 1000 lines long, and
420       the Informix one uses - and creates - auxiliary modules too).
421
422       See also ExtUtils::MakeMaker and ExtUtils::MM_Unix. Consider using
423       CPAN::MakeMaker in place of ExtUtils::MakeMaker.
424
425   README
426       The README file should describe what the driver is for, the pre-
427       requisites for the build process, the actual build process, how to
428       report errors, and who to report them to.
429
430       Users will find ways of breaking the driver build and test process
431       which you would never even have dreamed to be possible in your worst
432       nightmares. Therefore, you need to write this document defensively,
433       precisely and concisely.
434
435       As always, use the README from one of the established drivers as a
436       basis for your own; the version in DBD::Informix is worth a look as it
437       has been quite successful in heading off problems.
438
439       ·   Note that users will have versions of Perl and DBI that are both
440           older and newer than you expected, but this will seldom cause much
441           trouble.  When it does, it will be because you are using features
442           of DBI that are not supported in the version they are using.
443
444       ·   Note that users will have versions of the database software that
445           are both older and newer than you expected. You will save yourself
446           time in the long run if you can identify the range of versions
447           which have been tested and warn about versions which are not known
448           to be OK.
449
450       ·   Note that many people trying to install your driver will not be
451           experts in the database software.
452
453       ·   Note that many people trying to install your driver will not be
454           experts in C or Perl.
455
456   MANIFEST
457       The MANIFEST will be used by the Makefile's dist target to build the
458       distribution tar file that is uploaded to CPAN. It should list every
459       file that you want to include in your distribution, one per line.
460
461   lib/Bundle/DBD/Driver.pm
462       The CPAN module provides an extremely powerful bundle mechanism that
463       allows you to specify pre-requisites for your driver.
464
465       The primary pre-requisite is Bundle::DBI; you may want or need to add
466       some more. With the bundle set up correctly, the user can type:
467
468               perl -MCPAN -e 'install Bundle::DBD::Driver'
469
470       and Perl will download, compile, test and install all the Perl modules
471       needed to build your driver.
472
473       The prerequisite modules are listed in the "CONTENTS" section, with the
474       official name of the module followed by a dash and an informal name or
475       description.
476
477       ·   Listing Bundle::DBI as the main pre-requisite simplifies life.
478
479       ·   Don't forget to list your driver.
480
481       ·   Note that unless the DBMS is itself a Perl module, you cannot list
482           it as a pre-requisite in this file.
483
484       ·   You should keep the version of the bundle the same as the version
485           of your driver.
486
487       ·   You should add configuration management, copyright, and licencing
488           information at the top.
489
490       A suitable skeleton for this file is shown below.
491
492         package Bundle::DBD::Driver;
493
494         $VERSION = '0.01';
495
496         1;
497
498         __END__
499
500         =head1 NAME
501
502         Bundle::DBD::Driver - A bundle to install all DBD::Driver related modules
503
504         =head1 SYNOPSIS
505
506         C<perl -MCPAN -e 'install Bundle::DBD::Driver'>
507
508         =head1 CONTENTS
509
510         Bundle::DBI  - Bundle for DBI by TIMB (Tim Bunce)
511
512         DBD::Driver  - DBD::Driver by YOU (Your Name)
513
514         =head1 DESCRIPTION
515
516         This bundle includes all the modules used by the Perl Database
517         Interface (DBI) driver for Driver (DBD::Driver), assuming the
518         use of DBI version 1.13 or later, created by Tim Bunce.
519
520         If you've not previously used the CPAN module to install any
521         bundles, you will be interrogated during its setup phase.
522         But when you've done it once, it remembers what you told it.
523         You could start by running:
524
525           C<perl -MCPAN -e 'install Bundle::CPAN'>
526
527         =head1 SEE ALSO
528
529         Bundle::DBI
530
531         =head1 AUTHOR
532
533         Your Name E<lt>F<you@yourdomain.com>E<gt>
534
535         =head1 THANKS
536
537         This bundle was created by ripping off Bundle::libnet created by
538         Graham Barr E<lt>F<gbarr@ti.com>E<gt>, and radically simplified
539         with some information from Jochen Wiedmann E<lt>F<joe@ispsoft.de>E<gt>.
540         The template was then included in the DBI::DBD documentation by
541         Jonathan Leffler E<lt>F<jleffler@informix.com>E<gt>.
542
543         =cut
544
545   lib/DBD/Driver/Summary.pm
546       There is no substitute for taking the summary file from a driver that
547       was documented in the Perl book (such as DBD::Oracle or DBD::Informix
548       or DBD::ODBC, to name but three), and adapting it to describe the
549       facilities available via DBD::Driver when accessing the Driver
550       database.
551
552   Pure Perl version of Driver.pm
553       The Driver.pm file defines the Perl module DBD::Driver for your driver.
554       It will define a package DBD::Driver along with some version
555       information, some variable definitions, and a function "driver()" which
556       will have a more or less standard structure.
557
558       It will also define three sub-packages of DBD::Driver:
559
560       DBD::Driver::dr
561           with methods "connect()", "data_sources()" and "disconnect_all()";
562
563       DBD::Driver::db
564           with methods such as "prepare()";
565
566       DBD::Driver::st
567           with methods such as "execute()" and "fetch()".
568
569       The Driver.pm file will also contain the documentation specific to
570       DBD::Driver in the format used by perldoc.
571
572       In a pure Perl driver, the Driver.pm file is the core of the
573       implementation. You will need to provide all the key methods needed by
574       DBI.
575
576       Now let's take a closer look at an excerpt of File.pm as an example.
577       We ignore things that are common to any module (even non-DBI modules)
578       or really specific to the DBD::File package.
579
580       The DBD::Driver package
581
582       The header
583
584         package DBD::File;
585
586         use strict;
587         use vars qw($VERSION $drh);
588
589         $VERSION = "1.23.00"  # Version number of DBD::File
590
591       This is where the version number of your driver is specified, and is
592       where Makefile.PL looks for this information. Please ensure that any
593       other modules added with your driver are also version stamped so that
594       CPAN does not get confused.
595
596       It is recommended that you use a two-part (1.23) or three-part
597       (1.23.45) version number. Also consider the CPAN system, which gets
598       confused and considers version 1.10 to precede version 1.9, so that
599       using a raw CVS, RCS or SCCS version number is probably not appropriate
600       (despite being very common).
601
602       For Subversion you could use:
603
604         $VERSION = sprintf("12.%06d", q$Revision: 12345 $ =~ /(\d+)/o);
605
606       (use lots of leading zeros on the second portion so if you move the
607       code to a shared repository like svn.perl.org the much larger revision
608       numbers won't cause a problem, at least not for a few years).  For RCS
609       or CVS you can use:
610
611         $VERSION = sprintf "%d.%02d", '$Revision: 11.21 $ ' =~ /(\d+)\.(\d+)/;
612
613       which pads out the fractional part with leading zeros so all is well
614       (so long as you don't go past x.99)
615
616         $drh = undef;         # holds driver handle once initialized
617
618       This is where the driver handle will be stored, once created.  Note
619       that you may assume there is only one handle for your driver.
620
621       The driver constructor
622
623       The "driver()" method is the driver handle constructor. Note that the
624       "driver()" method is in the DBD::Driver package, not in one of the sub-
625       packages DBD::Driver::dr, DBD::Driver::db, or DBD::Driver::db.
626
627         sub driver
628         {
629             return $drh if $drh;      # already created - return same one
630             my ($class, $attr) = @_;
631
632             $class .= "::dr";
633
634             DBD::Driver::db->install_method('drv_example_dbh_method');
635             DBD::Driver::st->install_method('drv_example_sth_method');
636
637             # not a 'my' since we use it above to prevent multiple drivers
638             $drh = DBI::_new_drh($class, {
639                     'Name'        => 'File',
640                     'Version'     => $VERSION,
641                     'Attribution' => 'DBD::File by Jochen Wiedmann',
642                 })
643                 or return undef;
644
645             return $drh;
646         }
647
648       This is a reasonable example of how DBI implements its handles. There
649       are three kinds: driver handles (typically stored in $drh; from now on
650       called drh or $drh), database handles (from now on called dbh or $dbh)
651       and statement handles (from now on called sth or $sth).
652
653       The prototype of "DBI::_new_drh()" is
654
655         $drh = DBI::_new_drh($class, $public_attrs, $private_attrs);
656
657       with the following arguments:
658
659       $class
660           is typically the class for your driver, (for example,
661           "DBD::File::dr"), passed as the first argument to the "driver()"
662           method.
663
664       $public_attrs
665           is a hash ref to attributes like Name, Version, and Attribution.
666           These are processed and used by DBI. You had better not make any
667           assumptions about them nor should you add private attributes here.
668
669       $private_attrs
670           This is another (optional) hash ref with your private attributes.
671           DBI will store them and otherwise leave them alone.
672
673       The "DBI::_new_drh()" method and the "driver()" method both return
674       "undef" for failure (in which case you must look at $DBI::err and
675       $DBI::errstr for the failure information, because you have no driver
676       handle to use).
677
678       Using install_method() to expose driver-private methods
679
680           DBD::Foo::db->install_method($method_name, \%attr);
681
682       Installs the driver-private method named by $method_name into the DBI
683       method dispatcher so it can be called directly, avoiding the need to
684       use the func() method.
685
686       It is called as a static method on the driver class to which the method
687       belongs. The method name must begin with the corresponding registered
688       driver-private prefix. For example, for DBD::Oracle $method_name must
689       being with '"ora_"', and for DBD::AnyData it must begin with '"ad_"'.
690
691       The attributes can be used to provide fine control over how the DBI
692       dispatcher handles the dispatching of the method. However, at this
693       point, it's undocumented and very liable to change. (Volunteers to
694       polish up and document the interface are very welcome to get in touch
695       via dbi-dev@perl.org)
696
697       Methods installed using install_method default to the standard error
698       handling behaviour for DBI methods: clearing err and errstr before
699       calling the method, and checking for errors to trigger RaiseError etc.
700       on return. This differs from the default behaviour of func().
701
702       Note for driver authors: The DBD::Foo::xx->install_method call won't
703       work until the class-hierarchy has been setup. Normally the DBI looks
704       after that just after the driver is loaded. This means install_method()
705       can't be called at the time the driver is loaded unless the class-
706       hierarchy is set up first. The way to do that is to call the
707       setup_driver() method:
708
709           DBI->setup_driver('DBD::Foo');
710
711       before using install_method().
712
713       The CLONE special subroutine
714
715       Also needed here, in the DBD::Driver package, is a "CLONE()" method
716       that will be called by perl when an interpreter is cloned. All your
717       "CLONE()" method needs to do, currently, is clear the cached $drh so
718       the new interpreter won't start using the cached $drh from the old
719       interpreter:
720
721         sub CLONE {
722           undef $drh;
723         }
724
725       See
726       <http://search.cpan.org/dist/perl/pod/perlmod.pod#Making_your_module_threadsafe>
727       for details.
728
729       The DBD::Driver::dr package
730
731       The next lines of code look as follows:
732
733         package DBD::Driver::dr; # ====== DRIVER ======
734
735         $DBD::Driver::dr::imp_data_size = 0;
736
737       Note that no @ISA is needed here, or for the other DBD::Driver::*
738       classes, because the DBI takes care of that for you when the driver is
739       loaded.
740
741        *FIX ME* Explain what the imp_data_size is, so that implementors aren't
742        practicing cargo-cult programming.
743
744       The database handle constructor
745
746       The database handle constructor is the driver's (hence the changed
747       namespace) "connect()" method:
748
749         sub connect
750         {
751             my ($drh, $dr_dsn, $user, $auth, $attr) = @_;
752
753             # Some database specific verifications, default settings
754             # and the like can go here. This should only include
755             # syntax checks or similar stuff where it's legal to
756             # 'die' in case of errors.
757             # For example, many database packages requires specific
758             # environment variables to be set; this could be where you
759             # validate that they are set, or default them if they are not set.
760
761             my $driver_prefix = "drv_"; # the assigned prefix for this driver
762
763             # Process attributes from the DSN; we assume ODBC syntax
764             # here, that is, the DSN looks like var1=val1;...;varN=valN
765             foreach my $var ( split /;/, $dr_dsn ) {
766                 my ($attr_name, $attr_value) = split '=', $var, 2;
767                 return $drh->set_err($DBI::stderr, "Can't parse DSN part '$var'")
768                     unless defined $attr_value;
769
770                 # add driver prefix to attribute name if it doesn't have it already
771                 $attr_name = $driver_prefix.$attr_name
772                     unless $attr_name =~ /^$driver_prefix/o;
773
774                 # Store attribute into %$attr, replacing any existing value.
775                 # The DBI will STORE() these into $dbh after we've connected
776                 $attr->{$attr_name} = $attr_value;
777             }
778
779             # Get the attributes we'll use to connect.
780             # We use delete here because these no need to STORE them
781             my $db = delete $attr->{drv_database} || delete $attr->{drv_db}
782                 or return $drh->set_err($DBI::stderr, "No database name given in DSN '$dr_dsn'");
783             my $host = delete $attr->{drv_host} || 'localhost';
784             my $port = delete $attr->{drv_port} || 123456;
785
786             # Assume you can attach to your database via drv_connect:
787             my $connection = drv_connect($db, $host, $port, $user, $auth)
788                 or return $drh->set_err($DBI::stderr, "Can't connect to $dr_dsn: ...");
789
790             # create a 'blank' dbh (call superclass constructor)
791             my ($outer, $dbh) = DBI::_new_dbh($drh, { Name => $dr_dsn });
792
793             $dbh->STORE('Active', 1 );
794             $dbh->{drv_connection} = $connection;
795
796             return $outer;
797         }
798
799       This is mostly the same as in the driver handle constructor above.  The
800       arguments are described in DBI.
801
802       The constructor "DBI::_new_dbh()" is called, returning a database
803       handle.  The constructor's prototype is:
804
805         ($outer, $inner) = DBI::_new_dbh($drh, $public_attr, $private_attr);
806
807       with similar arguments to those in the driver handle constructor,
808       except that the $class is replaced by $drh. The Name attribute is a
809       standard DBI attribute (see "Database Handle Attributes" in DBI).
810
811       In scalar context, only the outer handle is returned.
812
813       Note the use of the "STORE()" method for setting the dbh attributes.
814       That's because within the driver code, the handle object you have is
815       the 'inner' handle of a tied hash, not the outer handle that the users
816       of your driver have.
817
818       Because you have the inner handle, tie magic doesn't get invoked when
819       you get or set values in the hash. This is often very handy for speed
820       when you want to get or set simple non-special driver-specific
821       attributes.
822
823       However, some attribute values, such as those handled by the DBI like
824       PrintError, don't actually exist in the hash and must be read via
825       "$h->FETCH($attrib)" and set via "$h->STORE($attrib, $value)".  If in
826       any doubt, use these methods.
827
828       The data_sources() method
829
830       The "data_sources()" method must populate and return a list of valid
831       data sources, prefixed with the "dbi:Driver" incantation that allows
832       them to be used in the first argument of the "DBI->connect()" method.
833       An example of this might be scanning the $HOME/.odbcini file on Unix
834       for ODBC data sources (DSNs).
835
836       As a trivial example, consider a fixed list of data sources:
837
838         sub data_sources
839         {
840             my($drh, $attr) = @_;
841             my(@list) = ();
842             # You need more sophisticated code than this to set @list...
843             push @list, "dbi:Driver:abc";
844             push @list, "dbi:Driver:def";
845             push @list, "dbi:Driver:ghi";
846             # End of code to set @list
847             return @list;
848         }
849
850       The disconnect_all() method
851
852       If you need to release any resources when the driver is unloaded, you
853       can provide a disconnect_all method.
854
855       Other driver handle methods
856
857       If you need any other driver handle methods, they can follow here.
858
859       Error handling
860
861       It is quite likely that something fails in the connect method.  With
862       DBD::File for example, you might catch an error when setting the
863       current directory to something not existent by using the (driver-
864       specific) f_dir attribute.
865
866       To report an error, you use the "set_err()" method:
867
868         $h->set_err($err, $errmsg, $state);
869
870       This will ensure that the error is recorded correctly and that
871       RaiseError and PrintError etc are handled correctly.
872
873       Typically you'll always use the method instance, aka your method's
874       first argument.
875
876       As "set_err()" always returns "undef" your error handling code can
877       usually be simplified to something like this:
878
879         return $h->set_err($err, $errmsg, $state) if ...;
880
881       The DBD::Driver::db package
882
883         package DBD::Driver::db; # ====== DATABASE ======
884
885         $DBD::Driver::db::imp_data_size = 0;
886
887       The statement handle constructor
888
889       There's nothing much new in the statement handle constructor, which is
890       the "prepare()" method:
891
892         sub prepare
893         {
894             my ($dbh, $statement, @attribs) = @_;
895
896             # create a 'blank' sth
897             my ($outer, $sth) = DBI::_new_sth($dbh, { Statement => $statement });
898
899             $sth->STORE('NUM_OF_PARAMS', ($statement =~ tr/?//));
900
901             $sth->{drv_params} = [];
902
903             return $outer;
904         }
905
906       This is still the same -- check the arguments and call the super class
907       constructor "DBI::_new_sth()". Again, in scalar context, only the outer
908       handle is returned. The Statement attribute should be cached as shown.
909
910       Note the prefix drv_ in the attribute names: it is required that all
911       your private attributes use a lowercase prefix unique to your driver.
912       As mentioned earlier in this document, the DBI contains a registry of
913       known driver prefixes and may one day warn about unknown attributes
914       that don't have a registered prefix.
915
916       Note that we parse the statement here in order to set the attribute
917       NUM_OF_PARAMS. The technique illustrated is not very reliable; it can
918       be confused by question marks appearing in quoted strings, delimited
919       identifiers or in SQL comments that are part of the SQL statement. We
920       could set NUM_OF_PARAMS in the "execute()" method instead because the
921       DBI specification explicitly allows a driver to defer this, but then
922       the user could not call "bind_param()".
923
924       Transaction handling
925
926       Pure Perl drivers will rarely support transactions. Thus your
927       "commit()" and "rollback()" methods will typically be quite simple:
928
929         sub commit
930         {
931             my ($dbh) = @_;
932             if ($dbh->FETCH('Warn')) {
933                 warn("Commit ineffective while AutoCommit is on");
934             }
935             0;
936         }
937
938         sub rollback {
939             my ($dbh) = @_;
940             if ($dbh->FETCH('Warn')) {
941                 warn("Rollback ineffective while AutoCommit is on");
942             }
943             0;
944         }
945
946       Or even simpler, just use the default methods provided by the DBI that
947       do nothing except return "undef".
948
949       The DBI's default "begin_work()" method can be used by inheritance.
950
951       The STORE() and FETCH() methods
952
953       These methods (that we have already used, see above) are called for
954       you, whenever the user does a:
955
956         $dbh->{$attr} = $val;
957
958       or, respectively,
959
960         $val = $dbh->{$attr};
961
962       See perltie for details on tied hash refs to understand why these
963       methods are required.
964
965       The DBI will handle most attributes for you, in particular attributes
966       like RaiseError or PrintError. All you have to do is handle your
967       driver's private attributes and any attributes, like AutoCommit and
968       ChopBlanks, that the DBI can't handle for you.
969
970       A good example might look like this:
971
972         sub STORE
973         {
974             my ($dbh, $attr, $val) = @_;
975             if ($attr eq 'AutoCommit') {
976                 # AutoCommit is currently the only standard attribute we have
977                 # to consider.
978                 if (!$val) { die "Can't disable AutoCommit"; }
979                 return 1;
980             }
981             if ($attr =~ m/^drv_/) {
982                 # Handle only our private attributes here
983                 # Note that we could trigger arbitrary actions.
984                 # Ideally we should warn about unknown attributes.
985                 $dbh->{$attr} = $val; # Yes, we are allowed to do this,
986                 return 1;             # but only for our private attributes
987             }
988             # Else pass up to DBI to handle for us
989             $dbh->SUPER::STORE($attr, $val);
990         }
991
992         sub FETCH
993         {
994             my ($dbh, $attr) = @_;
995             if ($attr eq 'AutoCommit') { return 1; }
996             if ($attr =~ m/^drv_/) {
997                 # Handle only our private attributes here
998                 # Note that we could trigger arbitrary actions.
999                 return $dbh->{$attr}; # Yes, we are allowed to do this,
1000                                       # but only for our private attributes
1001             }
1002             # Else pass up to DBI to handle
1003             $dbh->SUPER::FETCH($attr);
1004         }
1005
1006       The DBI will actually store and fetch driver-specific attributes (with
1007       all lowercase names) without warning or error, so there's actually no
1008       need to implement driver-specific any code in your "FETCH()" and
1009       "STORE()" methods unless you need extra logic/checks, beyond getting or
1010       setting the value.
1011
1012       Unless your driver documentation indicates otherwise, the return value
1013       of the "STORE()" method is unspecified and the caller shouldn't use
1014       that value.
1015
1016       Other database handle methods
1017
1018       As with the driver package, other database handle methods may follow
1019       here.  In particular you should consider a (possibly empty)
1020       "disconnect()" method and possibly a "quote()" method if DBI's default
1021       isn't correct for you. You may also need the "type_info_all()" and
1022       "get_info()" methods, as described elsewhere in this document.
1023
1024       Where reasonable use "$h->SUPER::foo()" to call the DBI's method in
1025       some or all cases and just wrap your custom behavior around that.
1026
1027       If you want to use private trace flags you'll probably want to be able
1028       to set them by name. To do that you'll need to define a
1029       "parse_trace_flag()" method (note that's "parse_trace_flag", singular,
1030       not "parse_trace_flags", plural).
1031
1032         sub parse_trace_flag {
1033             my ($h, $name) = @_;
1034             return 0x01000000 if $name eq 'foo';
1035             return 0x02000000 if $name eq 'bar';
1036             return 0x04000000 if $name eq 'baz';
1037             return 0x08000000 if $name eq 'boo';
1038             return 0x10000000 if $name eq 'bop';
1039             return $h->SUPER::parse_trace_flag($name);
1040         }
1041
1042       All private flag names must be lowercase, and all private flags must be
1043       in the top 8 of the 32 bits.
1044
1045       The DBD::Driver::st package
1046
1047       This package follows the same pattern the others do:
1048
1049         package DBD::Driver::st;
1050
1051         $DBD::Driver::st::imp_data_size = 0;
1052
1053       The execute() and bind_param() methods
1054
1055       This is perhaps the most difficult method because we have to consider
1056       parameter bindings here. In addition to that, there are a number of
1057       statement attributes which must be set for inherited DBI methods to
1058       function correctly (see "Statement attributes" below).
1059
1060       We present a simplified implementation by using the drv_params
1061       attribute from above:
1062
1063         sub bind_param
1064         {
1065             my ($sth, $pNum, $val, $attr) = @_;
1066             my $type = (ref $attr) ? $attr->{TYPE} : $attr;
1067             if ($type) {
1068                 my $dbh = $sth->{Database};
1069                 $val = $dbh->quote($sth, $type);
1070             }
1071             my $params = $sth->{drv_params};
1072             $params->[$pNum-1] = $val;
1073             1;
1074         }
1075
1076         sub execute
1077         {
1078             my ($sth, @bind_values) = @_;
1079
1080             # start of by finishing any previous execution if still active
1081             $sth->finish if $sth->FETCH('Active');
1082
1083             my $params = (@bind_values) ?
1084                 \@bind_values : $sth->{drv_params};
1085             my $numParam = $sth->FETCH('NUM_OF_PARAMS');
1086             return $sth->set_err($DBI::stderr, "Wrong number of parameters")
1087                 if @$params != $numParam;
1088             my $statement = $sth->{'Statement'};
1089             for (my $i = 0;  $i < $numParam;  $i++) {
1090                 $statement =~ s/?/$params->[$i]/; # XXX doesn't deal with quoting etc!
1091             }
1092             # Do anything ... we assume that an array ref of rows is
1093             # created and store it:
1094             $sth->{'drv_data'} = $data;
1095             $sth->{'drv_rows'} = @$data; # number of rows
1096             $sth->STORE('NUM_OF_FIELDS') = $numFields;
1097             $sth->{Active} = 1;
1098             @$data || '0E0';
1099         }
1100
1101       There are a number of things you should note here.
1102
1103       We initialize the NUM_OF_FIELDS and Active attributes here, because
1104       they are essential for "bind_columns()" to work.
1105
1106       We use attribute "$sth->{Statement}" which we created within
1107       "prepare()". The attribute "$sth->{Database}", which is nothing else
1108       than the dbh, was automatically created by DBI.
1109
1110       Finally, note that (as specified in the DBI specification) we return
1111       the string '0E0' instead of the number 0, so that the result tests true
1112       but equal to zero.
1113
1114         $sth->execute() or die $sth->errstr;
1115
1116       The execute_array(), execute_for_fetch() and bind_param_array() methods
1117
1118       In general, DBD's only need to implement "execute_for_fetch()" and
1119       "bind_param_array". DBI's default "execute_array()" will invoke the
1120       DBD's "execute_for_fetch()" as needed.
1121
1122       The following sequence describes the interaction between DBI
1123       "execute_array" and a DBD's "execute_for_fetch":
1124
1125       1.  App calls "$sth->execute_array(\%attrs, @array_of_arrays)"
1126
1127       2.  If @array_of_arrays was specified, DBI processes @array_of_arrays
1128           by calling DBD's "bind_param_array()". Alternately, App may have
1129           directly called "bind_param_array()"
1130
1131       3.  DBD validates and binds each array
1132
1133       4.  DBI retrieves the validated param arrays from DBD's ParamArray
1134           attribute
1135
1136       5.  DBI calls DBD's "execute_for_fetch($fetch_tuple_sub,
1137           \@tuple_status)", where &$fetch_tuple_sub is a closure to iterate
1138           over the returned ParamArray values, and "\@tuple_status" is an
1139           array to receive the disposition status of each tuple.
1140
1141       6.  DBD iteratively calls &$fetch_tuple_sub to retrieve parameter
1142           tuples to be added to its bulk database operation/request.
1143
1144       7.  when DBD reaches the limit of tuples it can handle in a single
1145           database operation/request, or the &$fetch_tuple_sub indicates no
1146           more tuples by returning undef, the DBD executes the bulk
1147           operation, and reports the disposition of each tuple in
1148           \@tuple_status.
1149
1150       8.  DBD repeats steps 6 and 7 until all tuples are processed.
1151
1152       E.g., here's the essence of DBD::Oracle's execute_for_fetch:
1153
1154              while (1) {
1155                  my @tuple_batch;
1156                  for (my $i = 0; $i < $batch_size; $i++) {
1157                       push @tuple_batch, [ @{$fetch_tuple_sub->() || last} ];
1158                  }
1159                  last unless @tuple_batch;
1160                  my $res = ora_execute_array($sth, \@tuple_batch,
1161                     scalar(@tuple_batch), $tuple_batch_status);
1162                  push @$tuple_status, @$tuple_batch_status;
1163              }
1164
1165       Note that DBI's default execute_array()/execute_for_fetch()
1166       implementation requires the use of positional (i.e., '?') placeholders.
1167       Drivers which require named placeholders must either emulate positional
1168       placeholders (e.g., see DBD::Oracle), or must implement their own
1169       execute_array()/execute_for_fetch() methods to properly sequence bound
1170       parameter arrays.
1171
1172       Fetching data
1173
1174       Only one method needs to be written for fetching data,
1175       "fetchrow_arrayref()".  The other methods, "fetchrow_array()",
1176       "fetchall_arrayref()", etc, as well as the database handle's "select*"
1177       methods are part of DBI, and call "fetchrow_arrayref()" as necessary.
1178
1179         sub fetchrow_arrayref
1180         {
1181             my ($sth) = @_;
1182             my $data = $sth->{drv_data};
1183             my $row = shift @$data;
1184             if (!$row) {
1185                 $sth->STORE(Active => 0); # mark as no longer active
1186                 return undef;
1187             }
1188             if ($sth->FETCH('ChopBlanks')) {
1189                 map { $_ =~ s/\s+$//; } @$row;
1190             }
1191             return $sth->_set_fbav($row);
1192         }
1193         *fetch = \&fetchrow_arrayref; # required alias for fetchrow_arrayref
1194
1195       Note the use of the method "_set_fbav()" -- this is required so that
1196       "bind_col()" and "bind_columns()" work.
1197
1198       If an error occurs which leaves the $sth in a state where remaining
1199       rows can't be fetched then Active should be turned off before the
1200       method returns.
1201
1202       The "rows()" method for this driver can be implemented like this:
1203
1204         sub rows { shift->{drv_rows} }
1205
1206       because it knows in advance how many rows it has fetched.
1207       Alternatively you could delete that method and so fallback to the DBI's
1208       own method which does the right thing based on the number of calls to
1209       "_set_fbav()".
1210
1211       The more_results method
1212
1213       If your driver doesn't support multiple result sets, then don't even
1214       implement this method.
1215
1216       Otherwise, this method needs to get the statement handle ready to fetch
1217       results from the next result set, if there is one. Typically you'd
1218       start with:
1219
1220           $sth->finish;
1221
1222       then you should delete all the attributes from the attribute cache that
1223       may no longer be relevant for the new result set:
1224
1225           delete $sth->{$_}
1226               for qw(NAME TYPE PRECISION SCALE ...);
1227
1228       for drivers written in C use:
1229
1230           hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD);
1231           hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD);
1232           hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD);
1233           hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD);
1234           hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD);
1235           hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD);
1236
1237       Don't forget to also delete, or update, any driver-private attributes
1238       that may not be correct for the next resultset.
1239
1240       The NUM_OF_FIELDS attribute is a special case. It should be set using
1241       STORE:
1242
1243           $sth->STORE(NUM_OF_FIELDS => 0); /* for DBI <= 1.53 */
1244           $sth->STORE(NUM_OF_FIELDS => $new_value);
1245
1246       for drivers written in C use this incantation:
1247
1248           /* Adjust NUM_OF_FIELDS - which also adjusts the row buffer size */
1249           DBIc_NUM_FIELDS(imp_sth) = 0; /* for DBI <= 1.53 */
1250           DBIc_STATE(imp_xxh)->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0,
1251               sv_2mortal(newSViv(mysql_num_fields(imp_sth->result)))
1252           );
1253
1254       For DBI versions prior to 1.54 you'll also need to explicitly adjust
1255       the number of elements in the row buffer array
1256       ("DBIc_FIELDS_AV(imp_sth)") to match the new result set. Fill any new
1257       values with newSV(0) not &sv_undef.  Alternatively you could free
1258       DBIc_FIELDS_AV(imp_sth) and set it to null, but that would mean
1259       bind_columns() wouldn't work across result sets.
1260
1261       Statement attributes
1262
1263       The main difference between dbh and sth attributes is, that you should
1264       implement a lot of attributes here that are required by the DBI, such
1265       as NAME, NULLABLE, TYPE, etc. See "Statement Handle Attributes" in DBI
1266       for a complete list.
1267
1268       Pay attention to attributes which are marked as read only, such as
1269       NUM_OF_PARAMS. These attributes can only be set the first time a
1270       statement is executed. If a statement is prepared, then executed
1271       multiple times, warnings may be generated.
1272
1273       You can protect against these warnings, and prevent the recalculation
1274       of attributes which might be expensive to calculate (such as the NAME
1275       and NAME_* attributes):
1276
1277           my $storedNumParams = $sth->FETCH('NUM_OF_PARAMS');
1278           if (!defined $storedNumParams or $storedNumFields < 0) {
1279               $sth->STORE('NUM_OF_PARAMS') = $numParams;
1280
1281               # Set other useful attributes that only need to be set once
1282               # for a statement, like $sth->{NAME} and $sth->{TYPE}
1283           }
1284
1285       One particularly important attribute to set correctly (mentioned in
1286       "ATTRIBUTES COMMON TO ALL HANDLES" in DBI is Active. Many DBI methods,
1287       including "bind_columns()", depend on this attribute.
1288
1289       Besides that the "STORE()" and "FETCH()" methods are mainly the same as
1290       above for dbh's.
1291
1292       Other statement methods
1293
1294       A trivial "finish()" method to discard stored data, reset any
1295       attributes (such as Active) and do "$sth->SUPER::finish()".
1296
1297       If you've defined a "parse_trace_flag()" method in ::db you'll also
1298       want it in ::st, so just alias it in:
1299
1300         *parse_trace_flag = \&DBD::foo:db::parse_trace_flag;
1301
1302       And perhaps some other methods that are not part of the DBI
1303       specification, in particular to make metadata available.  Remember that
1304       they must have names that begin with your drivers registered prefix so
1305       they can be installed using "install_method()".
1306
1307       If "DESTROY()" is called on a statement handle that's still active
1308       ("$sth->{Active}" is true) then it should effectively call "finish()".
1309
1310           sub DESTROY {
1311               my $sth = shift;
1312               $sth->finish if $sth->FETCH('Active');
1313           }
1314
1315   Tests
1316       The test process should conform as closely as possibly to the Perl
1317       standard test harness.
1318
1319       In particular, most (all) of the tests should be run in the t sub-
1320       directory, and should simply produce an "ok" when run under "make
1321       test".  For details on how this is done, see the Camel book and the
1322       section in Chapter 7, "The Standard Perl Library" on Test::Harness.
1323
1324       The tests may need to adapt to the type of database which is being used
1325       for testing, and to the privileges of the user testing the driver. For
1326       example, the DBD::Informix test code has to adapt in a number of places
1327       to the type of database to which it is connected as different Informix
1328       databases have different capabilities: some of the tests are for
1329       databases without transaction logs; others are for databases with a
1330       transaction log; some versions of the server have support for blobs, or
1331       stored procedures, or user-defined data types, and others do not.
1332
1333       When a complete file of tests must be skipped, you can provide a reason
1334       in a pseudo-comment:
1335
1336           if ($no_transactions_available)
1337           {
1338               print "1..0 # Skip: No transactions available\n";
1339               exit 0;
1340           }
1341
1342       Consider downloading the DBD::Informix code and look at the code in
1343       DBD/Informix/TestHarness.pm which is used throughout the DBD::Informix
1344       tests in the t sub-directory.
1345

CREATING A C/XS DRIVER

1347       Please also see the section under "CREATING A PURE PERL DRIVER"
1348       regarding the creation of the Makefile.PL.
1349
1350       Creating a new C/XS driver from scratch will always be a daunting task.
1351       You can and should greatly simplify your task by taking a good
1352       reference driver implementation and modifying that to match the
1353       database product for which you are writing a driver.
1354
1355       The de facto reference driver has been the one for DBD::Oracle written
1356       by Tim Bunce, who is also the author of the DBI package. The
1357       DBD::Oracle module is a good example of a driver implemented around a
1358       C-level API.
1359
1360       Nowadays it it seems better to base on DBD::ODBC, another driver
1361       maintained by Tim and Jeff Urlwin, because it offers a lot of metadata
1362       and seems to become the guideline for the future development. (Also as
1363       DBD::Oracle digs deeper into the Oracle 8 OCI interface it'll get even
1364       more hairy than it is now.)
1365
1366       The DBD::Informix driver is one driver implemented using embedded SQL
1367       instead of a function-based API.  DBD::Ingres may also be worth a look.
1368
1369   C/XS version of Driver.pm
1370       A lot of the code in the Driver.pm file is very similar to the code for
1371       pure Perl modules - see above.  However, there are also some subtle
1372       (and not so subtle) differences, including:
1373
1374       ·       The variables $DBD::Driver::{dr|db|st}::imp_data_size are not
1375               defined here, but in the XS code, because they declare the size
1376               of certain C structures.
1377
1378       ·       Some methods are typically moved to the XS code, in particular
1379               "prepare()", "execute()", "disconnect()", "disconnect_all()"
1380               and the "STORE()" and "FETCH()" methods.
1381
1382       ·       Other methods are still part of Driver.pm, but have callbacks
1383               to the XS code.
1384
1385       ·       If the driver-specific parts of the imp_drh_t structure need to
1386               be formally initialized (which does not seem to be a common
1387               requirement), then you need to add a call to an appropriate XS
1388               function in the driver method of "DBD::Driver::driver()", and
1389               you define the corresponding function in Driver.xs, and you
1390               define the C code in dbdimp.c and the prototype in dbdimp.h.
1391
1392               For example, DBD::Informix has such a requirement, and adds the
1393               following call after the call to "_new_drh()" in Informix.pm:
1394
1395                 DBD::Informix::dr::driver_init($drh);
1396
1397               and the following code in Informix.xs:
1398
1399                 # Initialize the DBD::Informix driver data structure
1400                 void
1401                 driver_init(drh)
1402                     SV *drh
1403                     CODE:
1404                     ST(0) = dbd_ix_dr_driver_init(drh) ? &sv_yes : &sv_no;
1405
1406               and the code in dbdimp.h declares:
1407
1408                 extern int dbd_ix_dr_driver_init(SV *drh);
1409
1410               and the code in dbdimp.ec (equivalent to dbdimp.c) defines:
1411
1412                 /* Formally initialize the DBD::Informix driver structure */
1413                 int
1414                 dbd_ix_dr_driver(SV *drh)
1415                 {
1416                     D_imp_drh(drh);
1417                     imp_drh->n_connections = 0;       /* No active connections */
1418                     imp_drh->current_connection = 0;  /* No current connection */
1419                     imp_drh->multipleconnections = (ESQLC_VERSION >= 600) ? True : False;
1420                     dbd_ix_link_newhead(&imp_drh->head);  /* Empty linked list of connections */
1421                     return 1;
1422                 }
1423
1424               DBD::Oracle has a similar requirement but gets around it by
1425               checking whether the private data part of the driver handle is
1426               all zeroed out, rather than add extra functions.
1427
1428       Now let's take a closer look at an excerpt from Oracle.pm (revised
1429       heavily to remove idiosyncrasies) as an example, ignoring things that
1430       were already discussed for pure Perl drivers.
1431
1432       The connect method
1433
1434       The connect method is the database handle constructor.  You could write
1435       either of two versions of this method: either one which takes
1436       connection attributes (new code) and one which ignores them (old code
1437       only).
1438
1439       If you ignore the connection attributes, then you omit all mention of
1440       the $auth variable (which is a reference to a hash of attributes), and
1441       the XS system manages the differences for you.
1442
1443         sub connect
1444         {
1445             my ($drh, $dbname, $user, $auth, $attr) = @_;
1446
1447             # Some database specific verifications, default settings
1448             # and the like following here. This should only include
1449             # syntax checks or similar stuff where it's legal to
1450             # 'die' in case of errors.
1451
1452             my $dbh = DBI::_new_dbh($drh, {
1453                     'Name'   => $dbname,
1454                 })
1455                 or return undef;
1456
1457             # Call the driver-specific function _login in Driver.xs file which
1458             # calls the DBMS-specific function(s) to connect to the database,
1459             # and populate internal handle data.
1460             DBD::Driver::db::_login($dbh, $dbname, $user, $auth, $attr)
1461                 or return undef;
1462
1463             $dbh;
1464         }
1465
1466       This is mostly the same as in the pure Perl case, the exception being
1467       the use of the private "_login()" callback, which is the function that
1468       will really connect to the database. It is implemented in Driver.xst
1469       (you should not implement it) and calls "dbd_db_login6()" or
1470       "dbd_db_login6_sv" from dbdimp.c. See below for details.
1471
1472       If your driver has driver-specific attributes which may be passed in
1473       the connect method and hence end up in $attr in "dbd_db_login6" then it
1474       is best to delete any you process so DBI does not send them again via
1475       STORE after connect. You can do this in C like this:
1476
1477         DBD_ATTRIB_DELETE(attr, "my_attribute_name",
1478                           strlen("my_attribute_name"));
1479
1480       However, prior to DBI subversion version 11605 (and fixed post 1.607)
1481       DBD_ATTRIB_DELETE segfaulted so if you cannot guarantee the DBI version
1482       will be post 1.607 you need to use:
1483
1484         hv_delete((HV*)SvRV(attr), "my_attribute_name",
1485                            strlen("my_attribute_name"), G_DISCARD);
1486
1487        *FIX ME* Discuss removing attributes in Perl code.
1488
1489       The disconnect_all method
1490
1491        *FIX ME* T.B.S
1492
1493       The data_sources method
1494
1495       If your "data_sources()" method can be implemented in pure Perl, then
1496       do so because it is easier than doing it in XS code (see the section
1497       above for pure Perl drivers).
1498
1499       If your "data_sources()" method must call onto compiled functions, then
1500       you will need to define dbd_dr_data_sources in your dbdimp.h file,
1501       which will trigger Driver.xst (in DBI v1.33 or greater) to generate the
1502       XS code that calls your actual C function (see the discussion below for
1503       details) and you do not code anything in Driver.pm to handle it.
1504
1505       The prepare method
1506
1507       The prepare method is the statement handle constructor, and most of it
1508       is not new. Like the "connect()" method, it now has a C callback:
1509
1510         package DBD::Driver::db; # ====== DATABASE ======
1511         use strict;
1512
1513         sub prepare
1514         {
1515             my ($dbh, $statement, $attribs) = @_;
1516
1517             # create a 'blank' sth
1518             my $sth = DBI::_new_sth($dbh, {
1519                 'Statement' => $statement,
1520                 })
1521                 or return undef;
1522
1523             # Call the driver-specific function _prepare in Driver.xs file
1524             # which calls the DBMS-specific function(s) to prepare a statement
1525             # and populate internal handle data.
1526             DBD::Driver::st::_prepare($sth, $statement, $attribs)
1527                 or return undef;
1528             $sth;
1529         }
1530
1531       The execute method
1532
1533        *FIX ME* T.B.S
1534
1535       The fetchrow_arrayref method
1536
1537        *FIX ME* T.B.S
1538
1539       Other methods?
1540
1541        *FIX ME* T.B.S
1542
1543   Driver.xs
1544       Driver.xs should look something like this:
1545
1546         #include "Driver.h"
1547
1548         DBISTATE_DECLARE;
1549
1550         INCLUDE: Driver.xsi
1551
1552         MODULE = DBD::Driver    PACKAGE = DBD::Driver::dr
1553
1554         /* Non-standard drh XS methods following here, if any.       */
1555         /* If none (the usual case), omit the MODULE line above too. */
1556
1557         MODULE = DBD::Driver    PACKAGE = DBD::Driver::db
1558
1559         /* Non-standard dbh XS methods following here, if any.       */
1560         /* Currently this includes things like _list_tables from     */
1561         /* DBD::mSQL and DBD::mysql.                                 */
1562
1563         MODULE = DBD::Driver    PACKAGE = DBD::Driver::st
1564
1565         /* Non-standard sth XS methods following here, if any.       */
1566         /* In particular this includes things like _list_fields from */
1567         /* DBD::mSQL and DBD::mysql for accessing metadata.          */
1568
1569       Note especially the include of Driver.xsi here: DBI inserts stub
1570       functions for almost all private methods here which will typically do
1571       much work for you.
1572
1573       Wherever you really have to implement something, it will call a private
1574       function in dbdimp.c, and this is what you have to implement.
1575
1576       You need to set up an extra routine if your driver needs to export
1577       constants of its own, analogous to the SQL types available when you
1578       say:
1579
1580         use DBI qw(:sql_types);
1581
1582        *FIX ME* T.B.S
1583
1584   Driver.h
1585       Driver.h is very simple and the operational contents should look like
1586       this:
1587
1588         #ifndef DRIVER_H_INCLUDED
1589         #define DRIVER_H_INCLUDED
1590
1591         #define NEED_DBIXS_VERSION 93    /* 93 for DBI versions 1.00 to 1.51+ */
1592         #define PERL_NO_GET_CONTEXT      /* if used require DBI 1.51+ */
1593
1594         #include <DBIXS.h>      /* installed by the DBI module  */
1595
1596         #include "dbdimp.h"
1597
1598         #include "dbivport.h"   /* see below                    */
1599
1600         #include <dbd_xsh.h>    /* installed by the DBI module  */
1601
1602         #endif /* DRIVER_H_INCLUDED */
1603
1604       The DBIXS.h header defines most of the interesting information that the
1605       writer of a driver needs.
1606
1607       The file dbd_xsh.h header provides prototype declarations for the C
1608       functions that you might decide to implement. Note that you should
1609       normally only define one of "dbd_db_login()", "dbd_db_login6()" or
1610       "dbd_db_login6_sv" unless you are intent on supporting really old
1611       versions of DBI (prior to DBI 1.06) as well as modern versions. The
1612       only standard, DBI-mandated functions that you need write are those
1613       specified in the dbd_xsh.h header. You might also add extra driver-
1614       specific functions in Driver.xs.
1615
1616       The dbivport.h file should be copied from the latest DBI release into
1617       your distribution each time you modify your driver. Its job is to allow
1618       you to enhance your code to work with the latest DBI API while still
1619       allowing your driver to be compiled and used with older versions of the
1620       DBI (for example, when the "DBIh_SET_ERR_CHAR()" macro was added to DBI
1621       1.41, an emulation of it was added to dbivport.h). This makes users
1622       happy and your life easier. Always read the notes in dbivport.h to
1623       check for any limitations in the emulation that you should be aware of.
1624
1625       With DBI v1.51 or better I recommend that the driver defines
1626       PERL_NO_GET_CONTEXT before DBIXS.h is included. This can significantly
1627       improve efficiency when running under a thread enabled perl. (Remember
1628       that the standard perl in most Linux distributions is built with
1629       threads enabled.  So is ActiveState perl for Windows, and perl built
1630       for Apache mod_perl2.)  If you do this there are some things to keep in
1631       mind:
1632
1633       ·   If PERL_NO_GET_CONTEXT is defined, then every function that calls
1634           the Perl API will need to start out with a "dTHX;" declaration.
1635
1636       ·   You'll know which functions need this, because the C compiler will
1637           complain that the undeclared identifier "my_perl" is used if and
1638           only if the perl you are using to develop and test your driver has
1639           threads enabled.
1640
1641       ·   If you don't remember to test with a thread-enabled perl before
1642           making a release it's likely that you'll get failure reports from
1643           users who are.
1644
1645       ·   For driver private functions it is possible to gain even more
1646           efficiency by replacing "dTHX;" with "pTHX_" prepended to the
1647           parameter list and then "aTHX_" prepended to the argument list
1648           where the function is called.
1649
1650       See "How multiple interpreters and concurrency are supported" in
1651       perlguts for additional information about PERL_NO_GET_CONTEXT.
1652
1653   Implementation header dbdimp.h
1654       This header file has two jobs:
1655
1656       First it defines data structures for your private part of the handles.
1657
1658       Second it defines macros that rename the generic names like
1659       "dbd_db_login()" to database specific names like "ora_db_login()". This
1660       avoids name clashes and enables use of different drivers when you work
1661       with a statically linked perl.
1662
1663       It also will have the important task of disabling XS methods that you
1664       don't want to implement.
1665
1666       Finally, the macros will also be used to select alternate
1667       implementations of some functions. For example, the "dbd_db_login()"
1668       function is not passed the attribute hash.
1669
1670       Since DBI v1.06, if a "dbd_db_login6()" macro is defined (for a
1671       function with 6 arguments), it will be used instead with the attribute
1672       hash passed as the sixth argument.
1673
1674       Since DBI post v1.607, if a "dbd_db_login6_sv()" macro is defined (for
1675       a function like dbd_db_login6 but with scalar pointers for the dbname,
1676       username and password), it will be used instead. This will allow your
1677       login6 function to see if there are any Unicode characters in the
1678       dbname.
1679
1680       People used to just pick Oracle's dbdimp.c and use the same names,
1681       structures and types. I strongly recommend against that. At first
1682       glance this saves time, but your implementation will be less readable.
1683       It was just hell when I had to separate DBI specific parts, Oracle
1684       specific parts, mSQL specific parts and mysql specific parts in
1685       DBD::mysql's dbdimp.h and dbdimp.c. (DBD::mysql was a port of DBD::mSQL
1686       which was based on DBD::Oracle.) [Seconded, based on the experience
1687       taking DBD::Informix apart, even though the version inherited in 1996
1688       was only based on DBD::Oracle.]
1689
1690       This part of the driver is your exclusive part. Rewrite it from
1691       scratch, so it will be clean and short: in other words, a better piece
1692       of code. (Of course keep an eye on other people's work.)
1693
1694         struct imp_drh_st {
1695             dbih_drc_t com;           /* MUST be first element in structure   */
1696             /* Insert your driver handle attributes here */
1697         };
1698
1699         struct imp_dbh_st {
1700             dbih_dbc_t com;           /* MUST be first element in structure   */
1701             /* Insert your database handle attributes here */
1702         };
1703
1704         struct imp_sth_st {
1705             dbih_stc_t com;           /* MUST be first element in structure   */
1706             /* Insert your statement handle attributes here */
1707         };
1708
1709         /*  Rename functions for avoiding name clashes; prototypes are  */
1710         /*  in dbd_xst.h                                                */
1711         #define dbd_init            drv_dr_init
1712         #define dbd_db_login6_sv    drv_db_login_sv
1713         #define dbd_db_do           drv_db_do
1714         ... many more here ...
1715
1716       These structures implement your private part of the handles.
1717
1718       You have to use the name "imp_dbh_{dr|db|st}" and the first field must
1719       be of type dbih_drc_t|_dbc_t|_stc_t and must be called "com".
1720
1721       You should never access these fields directly, except by using the
1722       DBIc_xxx() macros below.
1723
1724   Implementation source dbdimp.c
1725       Conventionally, dbdimp.c is the main implementation file (but
1726       DBD::Informix calls the file dbdimp.ec). This section includes a short
1727       note on each function that is used in the Driver.xsi template and thus
1728       has to be implemented.
1729
1730       Of course, you will probably also need to implement other support
1731       functions, which should usually be file static if they are placed in
1732       dbdimp.c. If they are placed in other files, you need to list those
1733       files in Makefile.PL (and MANIFEST) to handle them correctly.
1734
1735       It is wise to adhere to a namespace convention for your functions to
1736       avoid conflicts. For example, for a driver with prefix drv_, you might
1737       call externally visible functions dbd_drv_xxxx. You should also avoid
1738       non-constant global variables as much as possible to improve the
1739       support for threading.
1740
1741       Since Perl requires support for function prototypes (ANSI or ISO or
1742       Standard C), you should write your code using function prototypes too.
1743
1744       It is possible to use either the unmapped names such as "dbd_init()" or
1745       the mapped names such as "dbd_ix_dr_init()" in the dbdimp.c file.
1746       DBD::Informix uses the mapped names which makes it easier to identify
1747       where to look for linkage problems at runtime (which will report errors
1748       using the mapped names).
1749
1750       Most other drivers, and in particular DBD::Oracle, use the unmapped
1751       names in the source code which makes it a little easier to compare code
1752       between drivers and eases discussions on the dbi-dev mailing list.  The
1753       majority of the code fragments here will use the unmapped names.
1754
1755       Ultimately, you should provide implementations for most of the
1756       functions listed in the dbd_xsh.h header. The exceptions are optional
1757       functions (such as "dbd_st_rows()") and those functions with
1758       alternative signatures, such as "dbd_db_login6_sv", "dbd_db_login6()"
1759       and dbd_db_login(). Then you should only implement one of the
1760       alternatives, and generally the newer one of the alternatives.
1761
1762       The dbd_init method
1763
1764         #include "Driver.h"
1765
1766         DBISTATE_DECLARE;
1767
1768         void dbd_init(dbistate_t* dbistate)
1769         {
1770             DBISTATE_INIT;  /*  Initialize the DBI macros  */
1771         }
1772
1773       The "dbd_init()" function will be called when your driver is first
1774       loaded; the bootstrap command in "DBD::Driver::dr::driver()" triggers
1775       this, and the call is generated in the BOOT section of Driver.xst.
1776       These statements are needed to allow your driver to use the DBI macros.
1777       They will include your private header file dbdimp.h in turn.  Note that
1778       DBISTATE_INIT requires the name of the argument to "dbd_init()" to be
1779       called "dbistate()".
1780
1781       The dbd_drv_error method
1782
1783       You need a function to record errors so DBI can access them properly.
1784       You can call it whatever you like, but we'll call it "dbd_drv_error()"
1785       here.
1786
1787       The argument list depends on your database software; different systems
1788       provide different ways to get at error information.
1789
1790         static void dbd_drv_error(SV *h, int rc, const char *what)
1791         {
1792
1793       Note that h is a generic handle, may it be a driver handle, a database
1794       or a statement handle.
1795
1796             D_imp_xxh(h);
1797
1798       This macro will declare and initialize a variable imp_xxh with a
1799       pointer to your private handle pointer. You may cast this to to
1800       imp_drh_t, imp_dbh_t or imp_sth_t.
1801
1802       To record the error correctly, equivalent to the "set_err()" method,
1803       use one of the "DBIh_SET_ERR_CHAR(...)" or "DBIh_SET_ERR_SV(...)"
1804       macros, which were added in DBI 1.41:
1805
1806         DBIh_SET_ERR_SV(h, imp_xxh, err, errstr, state, method);
1807         DBIh_SET_ERR_CHAR(h, imp_xxh, err_c, err_i, errstr, state, method);
1808
1809       For "DBIh_SET_ERR_SV" the err, errstr, state, and method parameters are
1810       "SV*" (use &sv_undef instead of NULL).
1811
1812       For "DBIh_SET_ERR_CHAR" the err_c, errstr, state, method parameters are
1813       "char*".
1814
1815       The err_i parameter is an "IV" that's used instead of err_c if err_c is
1816       "Null".
1817
1818       The method parameter can be ignored.
1819
1820       The "DBIh_SET_ERR_CHAR" macro is usually the simplest to use when you
1821       just have an integer error code and an error message string:
1822
1823         DBIh_SET_ERR_CHAR(h, imp_xxh, Nullch, rc, what, Nullch, Nullch);
1824
1825       As you can see, any parameters that aren't relevant to you can be
1826       "Null".
1827
1828       To make drivers compatible with DBI < 1.41 you should be using
1829       dbivport.h as described in "Driver.h" above.
1830
1831       The (obsolete) macros such as "DBIh_EVENT2" should be removed from
1832       drivers.
1833
1834       The names "dbis" and "DBIS", which were used in previous versions of
1835       this document, should be replaced with the "DBIc_STATE(imp_xxh)" macro.
1836
1837       The name "DBILOGFP", which was also used in previous versions of this
1838       document, should be replaced by "DBIc_LOGPIO(imp_xxh)".
1839
1840       Your code should not call the C "<stdio.h>" I/O functions; you should
1841       use "PerlIO_printf()" as shown:
1842
1843             if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
1844                 PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar %s: %s\n",
1845                     foo, neatsvpv(errstr,0));
1846
1847       That's the first time we see how tracing works within a DBI driver.
1848       Make use of this as often as you can, but don't output anything at a
1849       trace level less than 3. Levels 1 and 2 are reserved for the DBI.
1850
1851       You can define up to 8 private trace flags using the top 8 bits of
1852       "DBIc_TRACE_FLAGS(imp)", that is: 0xFF000000. See the
1853       "parse_trace_flag()" method elsewhere in this document.
1854
1855       The dbd_dr_data_sources method
1856
1857       This method is optional; the support for it was added in DBI v1.33.
1858
1859       As noted in the discussion of Driver.pm, if the data sources can be
1860       determined by pure Perl code, do it that way. If, as in DBD::Informix,
1861       the information is obtained by a C function call, then you need to
1862       define a function that matches the prototype:
1863
1864         extern AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attrs);
1865
1866       An outline implementation for DBD::Informix follows, assuming that the
1867       "sqgetdbs()" function call shown will return up to 100 databases names,
1868       with the pointers to each name in the array dbsname and the name
1869       strings themselves being stores in dbsarea.
1870
1871         AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr)
1872         {
1873             int ndbs;
1874             int i;
1875             char *dbsname[100];
1876             char  dbsarea[10000];
1877             AV *av = Nullav;
1878
1879             if (sqgetdbs(&ndbs, dbsname, 100, dbsarea, sizeof(dbsarea)) == 0)
1880             {
1881                 av = NewAV();
1882                 av_extend(av, (I32)ndbs);
1883                 sv_2mortal((SV *)av);
1884                 for (i = 0; i < ndbs; i++)
1885                   av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i]));
1886             }
1887             return(av);
1888         }
1889
1890       The actual DBD::Informix implementation has a number of extra lines of
1891       code, logs function entry and exit, reports the error from
1892       "sqgetdbs()", and uses "#define"'d constants for the array sizes.
1893
1894       The dbd_db_login6 method
1895
1896         int dbd_db_login6_sv(SV* dbh, imp_dbh_t* imp_dbh, SV* dbname,
1897                              SV* user, SV* auth, SV *attr);
1898
1899         or
1900
1901         int dbd_db_login6(SV* dbh, imp_dbh_t* imp_dbh, char* dbname,
1902                          char* user, char* auth, SV *attr);
1903
1904       This function will really connect to the database. The argument dbh is
1905       the database handle. imp_dbh is the pointer to the handles private
1906       data, as is imp_xxx in "dbd_drv_error()" above. The arguments dbname,
1907       user, auth and attr correspond to the arguments of the driver handle's
1908       "connect()" method.
1909
1910       You will quite often use database specific attributes here, that are
1911       specified in the DSN. I recommend you parse the DSN (using Perl) within
1912       the "connect()" method and pass the segments of the DSN via the
1913       attributes parameter through "_login()" to "dbd_db_login6()".
1914
1915       Here's how you fetch them; as an example we use hostname attribute,
1916       which can be up to 12 characters long excluding null terminator:
1917
1918         SV** svp;
1919         STRLEN len;
1920         char* hostname;
1921
1922         if ( (svp = DBD_ATTRIB_GET_SVP(attr, "drv_hostname", 12)) && SvTRUE(*svp)) {
1923             hostname = SvPV(*svp, len);
1924             DBD_ATTRIB_DELETE(attr, "drv_hostname", 12); /* avoid later STORE */
1925         } else {
1926             hostname = "localhost";
1927         }
1928
1929       If you handle any driver specific attributes in the dbd_db_login6
1930       method you probably want to delete them from "attr" (as above with
1931       DBD_ATTRIB_DELETE). If you don't delete your handled attributes DBI
1932       will call "STORE" for each attribute after the connect/login and this
1933       is at best redundant for attributes you have already processed.
1934
1935       Note: Until revision 11605 (post DBI 1.607), there was a problem with
1936       DBD_ATTRIBUTE_DELETE so unless you require a DBI version after 1.607
1937       you need to replace each DBD_ATTRIBUTE_DELETE call with:
1938
1939         hv_delete((HV*)SvRV(attr), key, key_len, G_DISCARD)
1940
1941       Note that you can also obtain standard attributes such as AutoCommit
1942       and ChopBlanks from the attributes parameter, using "DBD_ATTRIB_GET_IV"
1943       for integer attributes.
1944
1945       If, for example, your database does not support transactions but
1946       AutoCommit is set off (requesting transaction support), then you can
1947       emulate a 'failure to connect'.
1948
1949       Now you should really connect to the database. In general, if the
1950       connection fails, it is best to ensure that all allocated resources are
1951       released so that the handle does not need to be destroyed separately.
1952       If you are successful (and possibly even if you fail but you have
1953       allocated some resources), you should use the following macros:
1954
1955         DBIc_IMPSET_on(imp_dbh);
1956
1957       This indicates that the driver (implementor) has allocated resources in
1958       the imp_dbh structure and that the implementors private
1959       "dbd_db_destroy()" function should be called when the handle is
1960       destroyed.
1961
1962         DBIc_ACTIVE_on(imp_dbh);
1963
1964       This indicates that the handle has an active connection to the server
1965       and that the "dbd_db_disconnect()" function should be called before the
1966       handle is destroyed.
1967
1968       Note that if you do need to fail, you should report errors via the drh
1969       or imp_drh rather than via dbh or imp_dbh because imp_dbh will be
1970       destroyed by the failure, so errors recorded in that handle will not be
1971       visible to DBI, and hence not the user either.
1972
1973       Note too, that the function is passed dbh and imp_dbh, and there is a
1974       macro "D_imp_drh_from_dbh" which can recover the imp_drh from the
1975       imp_dbh. However, there is no DBI macro to provide you with the drh
1976       given either the imp_dbh or the dbh or the imp_drh (and there's no way
1977       to recover the dbh given just the imp_dbh).
1978
1979       This suggests that, despite the above notes about "dbd_drv_error()"
1980       taking an "SV *", it may be better to have two error routines, one
1981       taking imp_dbh and one taking imp_drh instead. With care, you can
1982       factor most of the formatting code out so that these are small routines
1983       calling a common error formatter. See the code in DBD::Informix 1.05.00
1984       for more information.
1985
1986       The "dbd_db_login6()" function should return TRUE for success, FALSE
1987       otherwise.
1988
1989       Drivers implemented long ago may define the five-argument function
1990       "dbd_db_login()" instead of "dbd_db_login6()". The missing argument is
1991       the attributes. There are ways to work around the missing attributes,
1992       but they are ungainly; it is much better to use the 6-argument form.
1993       Even later drivers will use "dbd_db_login6_sv()" which provides the
1994       dbname, username and password as SVs.
1995
1996       The dbd_db_commit and dbd_db_rollback methods
1997
1998         int dbd_db_commit(SV *dbh, imp_dbh_t *imp_dbh);
1999         int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh);
2000
2001       These are used for commit and rollback. They should return TRUE for
2002       success, FALSE for error.
2003
2004       The arguments dbh and imp_dbh are the same as for "dbd_db_login6()"
2005       above; I will omit describing them in what follows, as they appear
2006       always.
2007
2008       These functions should return TRUE for success, FALSE otherwise.
2009
2010       The dbd_db_disconnect method
2011
2012       This is your private part of the "disconnect()" method. Any dbh with
2013       the ACTIVE flag on must be disconnected. (Note that you have to set it
2014       in "dbd_db_connect()" above.)
2015
2016         int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh);
2017
2018       The database handle will return TRUE for success, FALSE otherwise.  In
2019       any case it should do a:
2020
2021         DBIc_ACTIVE_off(imp_dbh);
2022
2023       before returning so DBI knows that "dbd_db_disconnect()" was executed.
2024
2025       Note that there's nothing to stop a dbh being disconnected while it
2026       still have active children. If your database API reacts badly to trying
2027       to use an sth in this situation then you'll need to add code like this
2028       to all sth methods:
2029
2030         if (!DBIc_ACTIVE(DBIc_PARENT_COM(imp_sth)))
2031           return 0;
2032
2033       Alternatively, you can add code to your driver to keep explicit track
2034       of the statement handles that exist for each database handle and
2035       arrange to destroy those handles before disconnecting from the
2036       database. There is code to do this in DBD::Informix. Similar comments
2037       apply to the driver handle keeping track of all the database handles.
2038
2039       Note that the code which destroys the subordinate handles should only
2040       release the associated database resources and mark the handles
2041       inactive; it does not attempt to free the actual handle structures.
2042
2043       This function should return TRUE for success, FALSE otherwise, but it
2044       is not clear what anything can do about a failure.
2045
2046       The dbd_db_discon_all method
2047
2048         int dbd_discon_all (SV *drh, imp_drh_t *imp_drh);
2049
2050       This function may be called at shutdown time. It should make best-
2051       efforts to disconnect all database handles - if possible. Some
2052       databases don't support that, in which case you can do nothing but
2053       return 'success'.
2054
2055       This function should return TRUE for success, FALSE otherwise, but it
2056       is not clear what anything can do about a failure.
2057
2058       The dbd_db_destroy method
2059
2060       This is your private part of the database handle destructor. Any dbh
2061       with the IMPSET flag on must be destroyed, so that you can safely free
2062       resources. (Note that you have to set it in "dbd_db_connect()" above.)
2063
2064         void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh)
2065         {
2066             DBIc_IMPSET_off(imp_dbh);
2067         }
2068
2069       The DBI Driver.xst code will have called "dbd_db_disconnect()" for you,
2070       if the handle is still 'active', before calling "dbd_db_destroy()".
2071
2072       Before returning the function must switch IMPSET to off, so DBI knows
2073       that the destructor was called.
2074
2075       A DBI handle doesn't keep references to its children. But children do
2076       keep references to their parents. So a database handle won't be
2077       "DESTROY"'d until all its children have been "DESTROY"'d.
2078
2079       The dbd_db_STORE_attrib method
2080
2081       This function handles
2082
2083         $dbh->{$key} = $value;
2084
2085       Its prototype is:
2086
2087         int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv,
2088                                 SV* valuesv);
2089
2090       You do not handle all attributes; on the contrary, you should not
2091       handle DBI attributes here: leave this to DBI. (There are two
2092       exceptions, AutoCommit and ChopBlanks, which you should care about.)
2093
2094       The return value is TRUE if you have handled the attribute or FALSE
2095       otherwise. If you are handling an attribute and something fails, you
2096       should call "dbd_drv_error()", so DBI can raise exceptions, if desired.
2097       If "dbd_drv_error()" returns, however, you have a problem: the user
2098       will never know about the error, because he typically will not check
2099       "$dbh->errstr()".
2100
2101       I cannot recommend a general way of going on, if "dbd_drv_error()"
2102       returns, but there are examples where even the DBI specification
2103       expects that you "croak()". (See the AutoCommit method in DBI.)
2104
2105       If you have to store attributes, you should either use your private
2106       data structure imp_xxx, the handle hash (via "(HV*)SvRV(dbh)"), or use
2107       the private imp_data.
2108
2109       The first is best for internal C values like integers or pointers and
2110       where speed is important within the driver. The handle hash is best for
2111       values the user may want to get/set via driver-specific attributes.
2112       The private imp_data is an additional "SV" attached to the handle. You
2113       could think of it as an unnamed handle attribute. It's not normally
2114       used.
2115
2116       The dbd_db_FETCH_attrib method
2117
2118       This is the counterpart of "dbd_db_STORE_attrib()", needed for:
2119
2120         $value = $dbh->{$key};
2121
2122       Its prototype is:
2123
2124         SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv);
2125
2126       Unlike all previous methods this returns an "SV" with the value. Note
2127       that you should normally execute "sv_2mortal()", if you return a
2128       nonconstant value. (Constant values are &sv_undef, &sv_no and &sv_yes.)
2129
2130       Note, that DBI implements a caching algorithm for attribute values.  If
2131       you think, that an attribute may be fetched, you store it in the dbh
2132       itself:
2133
2134         if (cacheit) /* cache value for later DBI 'quick' fetch? */
2135             hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
2136
2137       The dbd_st_prepare method
2138
2139       This is the private part of the "prepare()" method. Note that you must
2140       not really execute the statement here. You may, however, preparse and
2141       validate the statement, or do similar things.
2142
2143         int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement,
2144                            SV* attribs);
2145
2146       A typical, simple, possibility is to do nothing and rely on the perl
2147       "prepare()" code that set the Statement attribute on the handle. This
2148       attribute can then be used by "dbd_st_execute()".
2149
2150       If the driver supports placeholders then the NUM_OF_PARAMS attribute
2151       must be set correctly by "dbd_st_prepare()":
2152
2153         DBIc_NUM_PARAMS(imp_sth) = ...
2154
2155       If you can, you should also setup attributes like NUM_OF_FIELDS, NAME,
2156       etc. here, but DBI doesn't require that - they can be deferred until
2157       execute() is called. However, if you do, document it.
2158
2159       In any case you should set the IMPSET flag, as you did in
2160       "dbd_db_connect()" above:
2161
2162         DBIc_IMPSET_on(imp_sth);
2163
2164       The dbd_st_execute method
2165
2166       This is where a statement will really be executed.
2167
2168         int dbd_st_execute(SV* sth, imp_sth_t* imp_sth);
2169
2170       Note that you must be aware a statement may be executed repeatedly.
2171       Also, you should not expect that "finish()" will be called between two
2172       executions, so you might need code, like the following, near the start
2173       of the function:
2174
2175         if (DBIc_ACTIVE(imp_sth))
2176             dbd_st_finish(h, imp_sth);
2177
2178       If your driver supports the binding of parameters (it should!), but the
2179       database doesn't, you must do it here. This can be done as follows:
2180
2181         SV *svp;
2182         char* statement = DBD_ATTRIB_GET_PV(h, "Statement", 9, svp, "");
2183         int numParam = DBIc_NUM_PARAMS(imp_sth);
2184         int i;
2185
2186         for (i = 0; i < numParam; i++)
2187         {
2188             char* value = dbd_db_get_param(sth, imp_sth, i);
2189             /* It is your drivers task to implement dbd_db_get_param,    */
2190             /* it must be setup as a counterpart of dbd_bind_ph.         */
2191             /* Look for '?' and replace it with 'value'.  Difficult      */
2192             /* task, note that you may have question marks inside        */
2193             /* quotes and comments the like ...  :-(                     */
2194             /* See DBD::mysql for an example. (Don't look too deep into  */
2195             /* the example, you will notice where I was lazy ...)        */
2196         }
2197
2198       The next thing is to really execute the statement.
2199
2200       Note that you must set the attributes NUM_OF_FIELDS, NAME, etc when the
2201       statement is successfully executed if the driver has not already done
2202       so: they may be used even before a potential "fetchrow()".  In
2203       particular you have to tell DBI the number of fields that the statement
2204       has, because it will be used by DBI internally. Thus the function will
2205       typically ends with:
2206
2207         if (isSelectStatement) {
2208             DBIc_NUM_FIELDS(imp_sth) = numFields;
2209             DBIc_ACTIVE_on(imp_sth);
2210         }
2211
2212       It is important that the ACTIVE flag only be set for "SELECT"
2213       statements (or any other statements that can return many values from
2214       the database using a cursor-like mechanism). See "dbd_db_connect()"
2215       above for more explanations.
2216
2217       There plans for a preparse function to be provided by DBI, but this has
2218       not reached fruition yet.  Meantime, if you want to know how ugly it
2219       can get, try looking at the "dbd_ix_preparse()" in DBD::Informix
2220       dbdimp.ec and the related functions in iustoken.c and sqltoken.c.
2221
2222       The dbd_st_fetch method
2223
2224       This function fetches a row of data. The row is stored in in an array,
2225       of "SV"'s that DBI prepares for you. This has two advantages: it is
2226       fast (you even reuse the "SV"'s, so they don't have to be created after
2227       the first "fetchrow()"), and it guarantees that DBI handles
2228       "bind_cols()" for you.
2229
2230       What you do is the following:
2231
2232         AV* av;
2233         int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS
2234             is constant for this statement. There are drivers where this is
2235             not the case! */
2236         int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
2237         int i;
2238
2239         if (!fetch_new_row_of_data(...)) {
2240             ... /* check for error or end-of-data */
2241             DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */
2242             return Nullav;
2243         }
2244         /* get the fbav (field buffer array value) for this row       */
2245         /* it is very important to only call this after you know      */
2246         /* that you have a row of data to return.                     */
2247         av = DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
2248         for (i = 0; i < numFields; i++) {
2249             SV* sv = fetch_a_field(..., i);
2250             if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) {
2251                 /*  Remove white space from end (only) of sv  */
2252             }
2253             sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */
2254         }
2255         return av;
2256
2257       There's no need to use a "fetch_a_field()" function returning an "SV*".
2258       It's more common to use your database API functions to fetch the data
2259       as character strings and use code like this:
2260
2261         sv_setpvn(AvARRAY(av)[i], char_ptr, char_count);
2262
2263       "NULL" values must be returned as "undef". You can use code like this:
2264
2265         SvOK_off(AvARRAY(av)[i]);
2266
2267       The function returns the "AV" prepared by DBI for success or "Nullav"
2268       otherwise.
2269
2270        *FIX ME* Discuss what happens when there's no more data to fetch.
2271        Are errors permitted if another fetch occurs after the first fetch
2272        that reports no more data. (Permitted, not required.)
2273
2274       If an error occurs which leaves the $sth in a state where remaining
2275       rows can't be fetched then Active should be turned off before the
2276       method returns.
2277
2278       The dbd_st_finish3 method
2279
2280       The "$sth->finish()" method can be called if the user wishes to
2281       indicate that no more rows will be fetched even if the database has
2282       more rows to offer, and the DBI code can call the function when handles
2283       are being destroyed. See the DBI specification for more background
2284       details.
2285
2286       In both circumstances, the DBI code ends up calling the
2287       "dbd_st_finish3()" method (if you provide a mapping for
2288       "dbd_st_finish3()" in dbdimp.h), or "dbd_st_finish()" otherwise.  The
2289       difference is that "dbd_st_finish3()" takes a third argument which is
2290       an "int" with the value 1 if it is being called from a "destroy()"
2291       method and 0 otherwise.
2292
2293       Note that DBI v1.32 and earlier test on "dbd_db_finish3()" to call
2294       "dbd_st_finish3()"; if you provide "dbd_st_finish3()", either define
2295       "dbd_db_finish3()" too, or insist on DBI v1.33 or later.
2296
2297       All it needs to do is turn off the Active flag for the sth.  It will
2298       only be called by Driver.xst code, if the driver has set ACTIVE to on
2299       for the sth.
2300
2301       Outline example:
2302
2303         int dbd_st_finish3(SV* sth, imp_sth_t* imp_sth, int from_destroy) {
2304             if (DBIc_ACTIVE(imp_sth))
2305             {
2306                 /* close cursor or equivalent action */
2307                 DBIc_ACTIVE_off(imp_sth);
2308             }
2309             return 1;
2310         }
2311
2312       The from_destroy parameter is true if "dbd_st_finish3()" is being
2313       called from "DESTROY()" - and so the statement is about to be
2314       destroyed.  For many drivers there is no point in doing anything more
2315       than turning off the Active flag in this case.
2316
2317       The function returns TRUE for success, FALSE otherwise, but there isn't
2318       a lot anyone can do to recover if there is an error.
2319
2320       The dbd_st_destroy method
2321
2322       This function is the private part of the statement handle destructor.
2323
2324         void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth) {
2325             ... /* any clean-up that's needed */
2326             DBIc_IMPSET_off(imp_sth); /* let DBI know we've done it   */
2327         }
2328
2329       The DBI Driver.xst code will call "dbd_st_finish()" for you, if the sth
2330       has the ACTIVE flag set, before calling "dbd_st_destroy()".
2331
2332       The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
2333
2334       These functions correspond to "dbd_db_STORE()" and "dbd_db_FETCH()"
2335       attrib above, except that they are for statement handles.  See above.
2336
2337         int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv,
2338                                 SV* valuesv);
2339         SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv);
2340
2341       The dbd_bind_ph method
2342
2343       This function is internally used by the "bind_param()" method, the
2344       "bind_param_inout()" method and by the DBI Driver.xst code if
2345       "execute()" is called with any bind parameters.
2346
2347         int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param,
2348                          SV *value, IV sql_type, SV *attribs,
2349                          int is_inout, IV maxlen);
2350
2351       The param argument holds an "IV" with the parameter number (1, 2, ...).
2352       The value argument is the parameter value and sql_type is its type.
2353
2354       If your driver does not support "bind_param_inout()" then you should
2355       ignore maxlen and croak if is_inout is TRUE.
2356
2357       If your driver does support "bind_param_inout()" then you should note
2358       that value is the "SV" after dereferencing the reference passed to
2359       "bind_param_inout()".
2360
2361       In drivers of simple databases the function will, for example, store
2362       the value in a parameter array and use it later in "dbd_st_execute()".
2363       See the DBD::mysql driver for an example.
2364
2365       Implementing bind_param_inout support
2366
2367       To provide support for parameters bound by reference rather than by
2368       value, the driver must do a number of things.  First, and most
2369       importantly, it must note the references and stash them in its own
2370       driver structure.  Secondly, when a value is bound to a column, the
2371       driver must discard any previous reference bound to the column.  On
2372       each execute, the driver must evaluate the references and internally
2373       bind the values resulting from the references.  This is only applicable
2374       if the user writes:
2375
2376         $sth->execute;
2377
2378       If the user writes:
2379
2380         $sth->execute(@values);
2381
2382       then DBI automatically calls the binding code for each element of
2383       @values.  These calls are indistinguishable from explicit user calls to
2384       "bind_param()".
2385
2386   C/XS version of Makefile.PL
2387       The Makefile.PL file for a C/XS driver is similar to the code needed
2388       for a pure Perl driver, but there are a number of extra bits of
2389       information needed by the build system.
2390
2391       For example, the attributes list passed to "WriteMakefile()" needs to
2392       specify the object files that need to be compiled and built into the
2393       shared object (DLL). This is often, but not necessarily, just dbdimp.o
2394       (unless that should be dbdimp.obj because you're building on MS
2395       Windows).
2396
2397       Note that you can reliably determine the extension of the object files
2398       from the $Config{obj_ext} values, and there are many other useful
2399       pieces of configuration information lurking in that hash.  You get
2400       access to it with:
2401
2402           use Config;
2403
2404   Methods which do not need to be written
2405       The DBI code implements the majority of the methods which are accessed
2406       using the notation "DBI->function()", the only exceptions being
2407       "DBI->connect()" and "DBI->data_sources()" which require support from
2408       the driver.
2409
2410       The DBI code implements the following documented driver, database and
2411       statement functions which do not need to be written by the DBD driver
2412       writer.
2413
2414       $dbh->do()
2415           The default implementation of this function prepares, executes and
2416           destroys the statement.  This can be replaced if there is a better
2417           way to implement this, such as "EXECUTE IMMEDIATE" which can
2418           sometimes be used if there are no parameters.
2419
2420       $h->errstr()
2421       $h->err()
2422       $h->state()
2423       $h->trace()
2424           The DBD driver does not need to worry about these routines at all.
2425
2426       $h->{ChopBlanks}
2427           This attribute needs to be honored during "fetch()" operations, but
2428           does not need to be handled by the attribute handling code.
2429
2430       $h->{RaiseError}
2431           The DBD driver does not need to worry about this attribute at all.
2432
2433       $h->{PrintError}
2434           The DBD driver does not need to worry about this attribute at all.
2435
2436       $sth->bind_col()
2437           Assuming the driver uses the "DBIc_DBISTATE(imp_xxh)->get_fbav()"
2438           function (C drivers, see below), or the "$sth->_set_fbav($data)"
2439           method (Perl drivers) the driver does not need to do anything about
2440           this routine.
2441
2442       $sth->bind_columns()
2443           Regardless of whether the driver uses
2444           "DBIc_DBISTATE(imp_xxh)->get_fbav()", the driver does not need to
2445           do anything about this routine as it simply iteratively calls
2446           "$sth->bind_col()".
2447
2448       The DBI code implements a default implementation of the following
2449       functions which do not need to be written by the DBD driver writer
2450       unless the default implementation is incorrect for the Driver.
2451
2452       $dbh->quote()
2453           This should only be written if the database does not accept the
2454           ANSI SQL standard for quoting strings, with the string enclosed in
2455           single quotes and any embedded single quotes replaced by two
2456           consecutive single quotes.
2457
2458           For the two argument form of quote, you need to implement the
2459           "type_info()" method to provide the information that quote needs.
2460
2461       $dbh->ping()
2462           This should be implemented as a simple efficient way to determine
2463           whether the connection to the database is still alive. Typically
2464           code like this:
2465
2466             sub ping {
2467                 my $dbh = shift;
2468                 $sth = $dbh->prepare_cached(q{
2469                     select * from A_TABLE_NAME where 1=0
2470                 }) or return 0;
2471                 $sth->execute or return 0;
2472                 $sth->finish;
2473                 return 1;
2474             }
2475
2476           where A_TABLE_NAME is the name of a table that always exists (such
2477           as a database system catalogue).
2478

METADATA METHODS

2480       The exposition above ignores the DBI MetaData methods.  The metadata
2481       methods are all associated with a database handle.
2482
2483   Using DBI::DBD::Metadata
2484       The DBI::DBD::Metadata module is a good semi-automatic way for the
2485       developer of a DBD module to write the "get_info()" and "type_info()"
2486       functions quickly and accurately.
2487
2488       Generating the get_info method
2489
2490       Prior to DBI v1.33, this existed as the method "write_getinfo_pm()" in
2491       the DBI::DBD module. From DBI v1.33, it exists as the method
2492       "write_getinfo_pm()" in the DBI::DBD::Metadata module. This discussion
2493       assumes you have DBI v1.33 or later.
2494
2495       You examine the documentation for "write_getinfo_pm()" using:
2496
2497           perldoc DBI::DBD::Metadata
2498
2499       To use it, you need a Perl DBI driver for your database which
2500       implements the "get_info()" method. In practice, this means you need to
2501       install DBD::ODBC, an ODBC driver manager, and an ODBC driver for your
2502       database.
2503
2504       With the pre-requisites in place, you might type:
2505
2506           perl -MDBI::DBD::Metadata -we \
2507              "write_getinfo_pm (qw{ dbi:ODBC:foo_db username password Driver })"
2508
2509       The procedure writes to standard output the code that should be added
2510       to your Driver.pm file and the code that should be written to
2511       lib/DBD/Driver/GetInfo.pm.
2512
2513       You should review the output to ensure that it is sensible.
2514
2515       Generating the type_info method
2516
2517       Given the idea of the "write_getinfo_pm()" method, it was not hard to
2518       devise a parallel method, "write_typeinfo_pm()", which does the
2519       analogous job for the DBI "type_info_all()" metadata method. The
2520       "write_typeinfo_pm()" method was added to DBI v1.33.
2521
2522       You examine the documentation for "write_typeinfo_pm()" using:
2523
2524           perldoc DBI::DBD::Metadata
2525
2526       The setup is exactly analogous to the mechanism described in
2527       "Generating the get_info method".
2528
2529       With the pre-requisites in place, you might type:
2530
2531           perl -MDBI::DBD::Metadata -we \
2532              "write_typeinfo (qw{ dbi:ODBC:foo_db username password Driver })"
2533
2534       The procedure writes to standard output the code that should be added
2535       to your Driver.pm file and the code that should be written to
2536       lib/DBD/Driver/TypeInfo.pm.
2537
2538       You should review the output to ensure that it is sensible.
2539
2540   Writing DBD::Driver::db::get_info
2541       If you use the DBI::DBD::Metadata module, then the code you need is
2542       generated for you.
2543
2544       If you decide not to use the DBI::DBD::Metadata module, you should
2545       probably borrow the code from a driver that has done so (eg
2546       DBD::Informix from version 1.05 onwards) and crib the code from there,
2547       or look at the code that generates that module and follow that. The
2548       method in Driver.pm will be very simple; the method in
2549       lib/DBD/Driver/GetInfo.pm is not very much more complex unless your
2550       DBMS itself is much more complex.
2551
2552       Note that some of the DBI utility methods rely on information from the
2553       "get_info()" method to perform their operations correctly. See, for
2554       example, the "quote_identifier()" and quote methods, discussed below.
2555
2556   Writing DBD::Driver::db::type_info_all
2557       If you use the "DBI::DBD::Metadata" module, then the code you need is
2558       generated for you.
2559
2560       If you decide not to use the "DBI::DBD::Metadata" module, you should
2561       probably borrow the code from a driver that has done so (eg
2562       "DBD::Informix" from version 1.05 onwards) and crib the code from
2563       there, or look at the code that generates that module and follow that.
2564       The method in Driver.pm will be very simple; the method in
2565       lib/DBD/Driver/TypeInfo.pm is not very much more complex unless your
2566       DBMS itself is much more complex.
2567
2568   Writing DBD::Driver::db::type_info
2569       The guidelines on writing this method are still not really clear.  No
2570       sample implementation is available.
2571
2572   Writing DBD::Driver::db::table_info
2573        *FIX ME* The guidelines on writing this method have not been written yet.
2574        No sample implementation is available.
2575
2576   Writing DBD::Driver::db::column_info
2577        *FIX ME* The guidelines on writing this method have not been written yet.
2578        No sample implementation is available.
2579
2580   Writing DBD::Driver::db::primary_key_info
2581        *FIX ME* The guidelines on writing this method have not been written yet.
2582        No sample implementation is available.
2583
2584   Writing DBD::Driver::db::primary_key
2585        *FIX ME* The guidelines on writing this method have not been written yet.
2586        No sample implementation is available.
2587
2588   Writing DBD::Driver::db::foreign_key_info
2589        *FIX ME* The guidelines on writing this method have not been written yet.
2590        No sample implementation is available.
2591
2592   Writing DBD::Driver::db::tables
2593       This method generates an array of names in a format suitable for being
2594       embedded in SQL statements in places where a table name is expected.
2595
2596       If your database hews close enough to the SQL standard or if you have
2597       implemented an appropriate "table_info()" function and and the
2598       appropriate "quote_identifier()" function, then the DBI default version
2599       of this method will work for your driver too.
2600
2601       Otherwise, you have to write a function yourself, such as:
2602
2603           sub tables
2604           {
2605               my($dbh, $cat, $sch, $tab, $typ) = @_;
2606               my(@res);
2607               my($sth) = $dbh->table_info($cat, $sch, $tab, $typ);
2608               my(@arr);
2609               while (@arr = $sth->fetchrow_array)
2610               {
2611                   push @res, $dbh->quote_identifier($arr[0], $arr[1], $arr[2]);
2612               }
2613               return @res;
2614           }
2615
2616       See also the default implementation in DBI.pm.
2617
2618   Writing DBD::Driver::db::quote
2619       This method takes a value and converts it into a string suitable for
2620       embedding in an SQL statement as a string literal.
2621
2622       If your DBMS accepts the SQL standard notation for strings (single
2623       quotes around the string as a whole with any embedded single quotes
2624       doubled up), then you do not need to write this method as DBI provides
2625       a default method that does it for you.
2626
2627       If your DBMS uses an alternative notation or escape mechanism, then you
2628       need to provide an equivalent function. For example, suppose your DBMS
2629       used C notation with double quotes around the string and backslashes
2630       escaping both double quotes and backslashes themselves. Then you might
2631       write the function as:
2632
2633           sub quote
2634           {
2635               my($dbh, $str) = @_;
2636               $str =~ s/["\\]/\\$&/gmo;
2637               return qq{"$str"};
2638           }
2639
2640       Handling newlines and other control characters is left as an exercise
2641       for the reader.
2642
2643       This sample method ignores the $data_type indicator which is the
2644       optional second argument to the method.
2645
2646   Writing DBD::Driver::db::quote_identifier
2647       This method is called to ensure that the name of the given table (or
2648       other database object) can be embedded into an SQL statement without
2649       danger of misinterpretation. The result string should be usable in the
2650       text of an SQL statement as the identifier for a table.
2651
2652       If your DBMS accepts the SQL standard notation for quoted identifiers
2653       (which uses double quotes around the identifier as a whole, with any
2654       embedded double quotes doubled up) and accepts "schema"."identifier"
2655       (and "catalog"."schema"."identifier" when a catalog is specified), then
2656       you do not need to write this method as DBI provides a default method
2657       that does it for you.
2658
2659       In fact, even if your DBMS does not handle exactly that notation but
2660       you have implemented the "get_info()" method and it gives the correct
2661       responses, then it will work for you. If your database is fussier, then
2662       you need to implement your own version of the function.
2663
2664       For example, DBD::Informix has to deal with an environment variable
2665       DELIMIDENT. If it is not set, then the DBMS treats names enclosed in
2666       double quotes as strings rather than names, which is usually a syntax
2667       error. Additionally, the catalog portion of the name is separated from
2668       the schema and table by a different delimiter (colon instead of dot),
2669       and the catalog portion is never enclosed in quotes. (Fortunately,
2670       valid strings for the catalog will never contain weird characters that
2671       might need to be escaped, unless you count dots, dashes, slashes and
2672       at-signs as weird.) Finally, an Informix database can contain objects
2673       that cannot be accessed because they were created by a user with the
2674       DELIMIDENT environment variable set, but the current user does not have
2675       it set. By design choice, the "quote_identifier()" method encloses
2676       those identifiers in double quotes anyway, which generally triggers a
2677       syntax error, and the metadata methods which generate lists of tables
2678       etc omit those identifiers from the result sets.
2679
2680           sub quote_identifier
2681           {
2682               my($dbh, $cat, $sch, $obj) = @_;
2683               my($rv) = "";
2684               my($qq) = (defined $ENV{DELIMIDENT}) ? '"' : '';
2685               $rv .= qq{$cat:} if (defined $cat);
2686               if (defined $sch)
2687               {
2688                   if ($sch !~ m/^\w+$/o)
2689                   {
2690                       $qq = '"';
2691                       $sch =~ s/$qq/$qq$qq/gm;
2692                   }
2693                   $rv .= qq{$qq$sch$qq.};
2694               }
2695               if (defined $obj)
2696               {
2697                   if ($obj !~ m/^\w+$/o)
2698                   {
2699                       $qq = '"';
2700                       $obj =~ s/$qq/$qq$qq/gm;
2701                   }
2702                   $rv .= qq{$qq$obj$qq};
2703               }
2704               return $rv;
2705           }
2706
2707       Handling newlines and other control characters is left as an exercise
2708       for the reader.
2709
2710       Note that there is an optional fourth parameter to this function which
2711       is a reference to a hash of attributes; this sample implementation
2712       ignores that.
2713
2714       This sample implementation also ignores the single-argument variant of
2715       the method.
2716

TRACING

2718       Tracing in DBI is controlled with a combination of a trace level and a
2719       set of flags which together are known as the trace settings. The trace
2720       settings are stored in a single integer and divided into levels and
2721       flags by a set of masks ("DBIc_TRACE_LEVEL_MASK" and
2722       "DBIc_TRACE_FLAGS_MASK").
2723
2724       Each handle has it's own trace settings and so does the DBI. When you
2725       call a method the DBI merges the handles settings into its own for the
2726       duration of the call: the trace flags of the handle are OR'd into the
2727       trace flags of the DBI, and if the handle has a higher trace level then
2728       the DBI trace level is raised to match it. The previous DBI trace
2729       settings are restored when the called method returns.
2730
2731   Trace Level
2732       The trace level is the first 4 bits of the trace settings (masked by
2733       "DBIc_TRACE_FLAGS_MASK") and represents trace levels of 1 to 15. Do not
2734       output anything at trace levels less than 3 as they are reserved for
2735       DBI.
2736
2737       For advice on what to output at each level see "Trace Levels" in DBI.
2738
2739       To test for a trace level you can use the "DBIc_TRACE_LEVEL" macro like
2740       this:
2741
2742         if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) {
2743             PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar");
2744         }
2745
2746       Also note the use of PerlIO_printf which you should always use for
2747       tracing and never the C "stdio.h" I/O functions.
2748
2749   Trace Flags
2750       Trace flags are used to enable tracing of specific activities within
2751       the DBI and drivers. The DBI defines some trace flags and drivers can
2752       define others. DBI trace flag names begin with a capital letter and
2753       driver specific names begin with a lowercase letter. For a list of DBI
2754       defined trace flags see "Trace Flags" in DBI.
2755
2756       If you want to use private trace flags you'll probably want to be able
2757       to set them by name. Drivers are expected to override the
2758       parse_trace_flag (note the singular) and check if $trace_flag_name is a
2759       driver specific trace flags and, if not, then call the DBIs default
2760       parse_trace_flag(). To do that you'll need to define a
2761       parse_trace_flag() method like this:
2762
2763         sub parse_trace_flag {
2764             my ($h, $name) = @_;
2765             return 0x01000000 if $name eq 'foo';
2766             return 0x02000000 if $name eq 'bar';
2767             return 0x04000000 if $name eq 'baz';
2768             return 0x08000000 if $name eq 'boo';
2769             return 0x10000000 if $name eq 'bop';
2770             return $h->SUPER::parse_trace_flag($name);
2771         }
2772
2773       All private flag names must be lowercase, and all private flags must be
2774       in the top 8 of the 32 bits of "DBIc_TRACE_FLAGS(imp)" i.e.,
2775       0xFF000000.
2776
2777       If you've defined a parse_trace_flag() method in ::db you'll also want
2778       it in ::st, so just alias it in:
2779
2780         *parse_trace_flag = \&DBD::foo:db::parse_trace_flag;
2781
2782       You may want to act on the current 'SQL' trace flag that DBI defines to
2783       output SQL prepared/executed as DBI currently does not do SQL tracing.
2784
2785   Trace Macros
2786       Access to the trace level and trace flags is via a set of macros.
2787
2788         DBIc_TRACE_SETTINGS(imp) returns the trace settings
2789         DBIc_TRACE_LEVEL(imp) returns the trace level
2790         DBIc_TRACE_FLAGS(imp) returns the trace flags
2791         DBIc_TRACE(imp, flags, flaglevel, level)
2792
2793         e.g.,
2794
2795         DBIc_TRACE(imp, 0, 0, 4)
2796           if level >= 4
2797
2798         DBIc_TRACE(imp, DBDtf_FOO, 2, 4)
2799           if tracing DBDtf_FOO & level>=2 or level>=4
2800
2801         DBIc_TRACE(imp, DBDtf_FOO, 2, 0)
2802           as above but never trace just due to level
2803

WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE

2805       Study Oraperl.pm (supplied with DBD::Oracle) and Ingperl.pm (supplied
2806       with DBD::Ingres) and the corresponding dbdimp.c files for ideas.
2807
2808       Note that the emulation code sets "$dbh->{CompatMode} = 1;" for each
2809       connection so that the internals of the driver can implement behaviour
2810       compatible with the old interface when dealing with those handles.
2811
2812   Setting emulation perl variables
2813       For example, ingperl has a $sql_rowcount variable. Rather than try to
2814       manually update this in Ingperl.pm it can be done faster in C code.  In
2815       "dbd_init()":
2816
2817         sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI);
2818
2819       In the relevant places do:
2820
2821         if (DBIc_COMPAT(imp_sth))     /* only do this for compatibility mode handles */
2822             sv_setiv(sql_rowcount, the_row_count);
2823

OTHER MISCELLANEOUS INFORMATION

2825   The imp_xyz_t types
2826       Any handle has a corresponding C structure filled with private data.
2827       Some of this data is reserved for use by DBI (except for using the DBIc
2828       macros below), some is for you. See the description of the dbdimp.h
2829       file above for examples. Most functions in dbdimp.c are passed both the
2830       handle "xyz" and a pointer to "imp_xyz". In rare cases, however, you
2831       may use the following macros:
2832
2833       D_imp_dbh(dbh)
2834           Given a function argument dbh, declare a variable imp_dbh and
2835           initialize it with a pointer to the handles private data. Note:
2836           This must be a part of the function header, because it declares a
2837           variable.
2838
2839       D_imp_sth(sth)
2840           Likewise for statement handles.
2841
2842       D_imp_xxx(h)
2843           Given any handle, declare a variable imp_xxx and initialize it with
2844           a pointer to the handles private data. It is safe, for example, to
2845           cast imp_xxx to "imp_dbh_t*", if "DBIc_TYPE(imp_xxx) == DBIt_DB".
2846           (You can also call "sv_derived_from(h, "DBI::db")", but that's much
2847           slower.)
2848
2849       D_imp_dbh_from_sth
2850           Given a imp_sth, declare a variable imp_dbh and initialize it with
2851           a pointer to the parent database handle's implementors structure.
2852
2853   Using DBIc_IMPSET_on
2854       The driver code which initializes a handle should use
2855       "DBIc_IMPSET_on()" as soon as its state is such that the cleanup code
2856       must be called.  When this happens is determined by your driver code.
2857
2858       Failure to call this can lead to corruption of data structures.
2859
2860       For example, DBD::Informix maintains a linked list of database handles
2861       in the driver, and within each handle, a linked list of statements.
2862       Once a statement is added to the linked list, it is crucial that it is
2863       cleaned up (removed from the list). When DBIc_IMPSET_on() was being
2864       called too late, it was able to cause all sorts of problems.
2865
2866   Using DBIc_is(), DBIc_has(), DBIc_on() and DBIc_off()
2867       Once upon a long time ago, the only way of handling the internal DBI
2868       boolean flags/attributes was through macros such as:
2869
2870         DBIc_WARN       DBIc_WARN_on        DBIc_WARN_off
2871         DBIc_COMPAT     DBIc_COMPAT_on      DBIc_COMPAT_off
2872
2873       Each of these took an imp_xxh pointer as an argument.
2874
2875       Since then, new attributes have been added such as ChopBlanks,
2876       RaiseError and PrintError, and these do not have the full set of
2877       macros. The approved method for handling these is now the four macros:
2878
2879         DBIc_is(imp, flag)
2880         DBIc_has(imp, flag)       an alias for DBIc_is
2881         DBIc_on(imp, flag)
2882         DBIc_off(imp, flag)
2883         DBIc_set(imp, flag, on)   set if on is true, else clear
2884
2885       Consequently, the "DBIc_XXXXX" family of macros is now mostly
2886       deprecated and new drivers should avoid using them, even though the
2887       older drivers will probably continue to do so for quite a while yet.
2888       However...
2889
2890       There is an important exception to that. The ACTIVE and IMPSET flags
2891       should be set via the "DBIc_ACTIVE_on()" and "DBIc_IMPSET_on()" macros,
2892       and unset via the "DBIc_ACTIVE_off()" and "DBIc_IMPSET_off()" macros.
2893
2894   Using the get_fbav() method
2895       THIS IS CRITICAL for C/XS drivers.
2896
2897       The "$sth->bind_col()" and "$sth->bind_columns()" documented in the DBI
2898       specification do not have to be implemented by the driver writer
2899       because DBI takes care of the details for you.
2900
2901       However, the key to ensuring that bound columns work is to call the
2902       function "DBIc_DBISTATE(imp_xxh)->get_fbav()" in the code which fetches
2903       a row of data.
2904
2905       This returns an "AV", and each element of the "AV" contains the "SV"
2906       which should be set to contain the returned data.
2907
2908       The pure Perl equivalent is the "$sth->_set_fbav($data)" method, as
2909       described in the part on pure Perl drivers.
2910
2911   Casting strings to Perl types based on a SQL type
2912       DBI from 1.611 (and DBIXS_REVISION 13606) defines the
2913       sql_type_cast_svpv method which may be used to cast a string
2914       representation of a value to a more specific Perl type based on a SQL
2915       type. You should consider using this method when processing bound
2916       column data as it provides some support for the TYPE bind_col attribute
2917       which is rarely used in drivers.
2918
2919         int sql_type_cast_svpv(pTHX_ SV *sv, int sql_type, U32 flags, void *v)
2920
2921       "sv" is what you would like cast, "sql_type" is one of the DBI defined
2922       SQL types (e.g., "SQL_INTEGER") and "flags" is a bitmask as follows:
2923
2924       DBIstcf_STRICT
2925           If set this indicates you want an error state returned if the cast
2926           cannot be performed.
2927
2928       DBIstcf_DISCARD_STRING
2929           If set and the pv portion of the "sv" is cast then this will cause
2930           sv's pv to be freed up.
2931
2932       sql_type_cast_svpv returns the following states:
2933
2934        -2 sql_type is not handled - sv not changed
2935        -1 sv is undef, sv not changed
2936         0 sv could not be cast cleanly and DBIstcf_STRICT was specified
2937         1 sv could not be case cleanly and DBIstcf_STRICT was not specified
2938         2 sv was cast ok
2939
2940       The current implementation of sql_type_cast_svpv supports
2941       "SQL_INTEGER", "SQL_DOUBLE" and "SQL_NUMERIC". "SQL_INTEGER" uses
2942       sv_2iv and hence may set IV, UV or NV depending on the number.
2943       "SQL_DOUBLE" uses sv_2nv so may set NV and "SQL_NUMERIC" will set IV or
2944       UV or NV.
2945
2946       DBIstcf_STRICT should be implemented as the StrictlyTyped attribute and
2947       DBIstcf_DISCARD_STRING implemented as the DiscardString attribute to
2948       the bind_col method and both default to off.
2949
2950       See DBD::Oracle for an example of how this is used.
2951

SUBCLASSING DBI DRIVERS

2953       This is definitely an open subject. It can be done, as demonstrated by
2954       the DBD::File driver, but it is not as simple as one might think.
2955
2956       (Note that this topic is different from subclassing the DBI. For an
2957       example of that, see the t/subclass.t file supplied with the DBI.)
2958
2959       The main problem is that the dbh's and sth's that your "connect()" and
2960       "prepare()" methods return are not instances of your DBD::Driver::db or
2961       DBD::Driver::st packages, they are not even derived from it.  Instead
2962       they are instances of the DBI::db or DBI::st classes or a derived
2963       subclass. Thus, if you write a method "mymethod()" and do a
2964
2965         $dbh->mymethod()
2966
2967       then the autoloader will search for that method in the package DBI::db.
2968       Of course you can instead to a
2969
2970         $dbh->func('mymethod')
2971
2972       and that will indeed work, even if "mymethod()" is inherited, but not
2973       without additional work. Setting @ISA is not sufficient.
2974
2975   Overwriting methods
2976       The first problem is, that the "connect()" method has no idea of
2977       subclasses. For example, you cannot implement base class and subclass
2978       in the same file: The "install_driver()" method wants to do a
2979
2980         require DBD::Driver;
2981
2982       In particular, your subclass has to be a separate driver, from the view
2983       of DBI, and you cannot share driver handles.
2984
2985       Of course that's not much of a problem. You should even be able to
2986       inherit the base classes "connect()" method. But you cannot simply
2987       overwrite the method, unless you do something like this, quoted from
2988       DBD::CSV:
2989
2990         sub connect ($$;$$$) {
2991             my ($drh, $dbname, $user, $auth, $attr) = @_;
2992
2993             my $this = $drh->DBD::File::dr::connect($dbname, $user, $auth, $attr);
2994             if (!exists($this->{csv_tables})) {
2995                 $this->{csv_tables} = {};
2996             }
2997
2998             $this;
2999         }
3000
3001       Note that we cannot do a
3002
3003         $drh->SUPER::connect($dbname, $user, $auth, $attr);
3004
3005       as we would usually do in a an OO environment, because $drh is an
3006       instance of DBI::dr. And note, that the "connect()" method of DBD::File
3007       is able to handle subclass attributes. See the description of Pure Perl
3008       drivers above.
3009
3010       It is essential that you always call superclass method in the above
3011       manner. However, that should do.
3012
3013   Attribute handling
3014       Fortunately the DBI specifications allow a simple, but still performant
3015       way of handling attributes. The idea is based on the convention that
3016       any driver uses a prefix driver_ for its private methods. Thus it's
3017       always clear whether to pass attributes to the super class or not. For
3018       example, consider this "STORE()" method from the DBD::CSV class:
3019
3020         sub STORE {
3021             my ($dbh, $attr, $val) = @_;
3022             if ($attr !~ /^driver_/) {
3023                 return $dbh->DBD::File::db::STORE($attr, $val);
3024             }
3025             if ($attr eq 'driver_foo') {
3026             ...
3027         }
3028

AUTHORS

3030       Jonathan Leffler <jleffler@us.ibm.com> (previously
3031       <jleffler@informix.com>), Jochen Wiedmann <joe@ispsoft.de>, Steffen
3032       Goeldner <sgoeldner@cpan.org>, and Tim Bunce <dbi-users@perl.org>.
3033
3034
3035
3036perl v5.12.1                      2010-06-08                       DBI::DBD(3)
Impressum