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>. You can find
194       a reasonable example of a META.yml in DBD::ODBC.
195
196       The lib/Bundle/DBD/Driver.pm file allows you to specify other Perl
197       modules on which yours depends in a format that allows someone to type
198       a simple command and ensure that all the pre-requisites are in place as
199       well as building your driver.
200
201       The lib/DBD/Driver/Summary.pm file contains (an updated version of) the
202       information that was included - or that would have been included - in
203       the appendices of the Cheetah book as a summary of the abilities of
204       your driver and the associated database.
205
206       The files in the t subdirectory are unit tests for your driver.  You
207       should write your tests as stringently as possible, while taking into
208       account the diversity of installations that you can encounter:
209
210       ·   Your tests should not casually modify operational databases.
211
212       ·   You should never damage existing tables in a database.
213
214       ·   You should code your tests to use a constrained name space within
215           the database. For example, the tables (and all other named objects)
216           that are created could all begin with 'dbd_drv_'.
217
218       ·   At the end of a test run, there should be no testing objects left
219           behind in the database.
220
221       ·   If you create any databases, you should remove them.
222
223       ·   If your database supports temporary tables that are automatically
224           removed at the end of a session, then exploit them as often as
225           possible.
226
227       ·   Try to make your tests independent of each other. If you have a
228           test t/t11dowhat.t that depends upon the successful running of
229           t/t10thingamy.t, people cannot run the single test case
230           t/t11dowhat.t. Further, running t/t11dowhat.t twice in a row is
231           likely to fail (at least, if t/t11dowhat.t modifies the database at
232           all) because the database at the start of the second run is not
233           what you saw at the start of the first run.
234
235       ·   Document in your README file what you do, and what privileges
236           people need to do it.
237
238       ·   You can, and probably should, sequence your tests by including a
239           test number before an abbreviated version of the test name; the
240           tests are run in the order in which the names are expanded by
241           shell-style globbing.
242
243       ·   It is in your interests to ensure that your tests work as widely as
244           possible.
245
246       Many drivers also install sub-modules DBD::Driver::SubModule for any of
247       a variety of different reasons, such as to support the metadata methods
248       (see the discussion of "METADATA METHODS" below). Such sub-modules are
249       conventionally stored in the directory lib/DBD/Driver. The module
250       itself would usually be in a file SubModule.pm. All such sub-modules
251       should themselves be version stamped (see the discussions far below).
252
253       Extra files needed by C/XS drivers
254
255       The software for a C/XS driver will typically contain at least four
256       extra files that are not relevant to a pure Perl driver.
257
258       ·   Driver.xs
259
260       ·   Driver.h
261
262       ·   dbdimp.h
263
264       ·   dbdimp.c
265
266       The Driver.xs file is used to generate C code that Perl can call to
267       gain access to the C functions you write that will, in turn, call down
268       onto your database software.
269
270       The Driver.h header is a stylized header that ensures you can access
271       the necessary Perl and DBI macros, types, and function declarations.
272
273       The dbdimp.h is used to specify which functions have been implemented
274       by your driver.
275
276       The dbdimp.c file is where you write the C code that does the real work
277       of translating between Perl-ish data types and what the database
278       expects to use and return.
279
280       There are some (mainly small, but very important) differences between
281       the contents of Makefile.PL and Driver.pm for pure Perl and C/XS
282       drivers, so those files are described both in the section on creating a
283       pure Perl driver and in the section on creating a C/XS driver.
284
285       Obviously, you can add extra source code files to the list.
286
287   Requirements on a driver and driver writer
288       To be remotely useful, your driver must be implemented in a format that
289       allows it to be distributed via CPAN, the Comprehensive Perl Archive
290       Network (<http://www.cpan.org/> and <http://search.cpan.org>).  Of
291       course, it is easier if you do not have to meet this criterion, but you
292       will not be able to ask for much help if you do not do so, and no-one
293       is likely to want to install your module if they have to learn a new
294       installation mechanism.
295

CREATING A PURE PERL DRIVER

297       Writing a pure Perl driver is surprisingly simple. However, there are
298       some problems you should be aware of. The best option is of course
299       picking up an existing driver and carefully modifying one method after
300       the other.
301
302       Also look carefully at DBD::AnyData and DBD::Template.
303
304       As an example we take a look at the DBD::File driver, a driver for
305       accessing plain files as tables, which is part of the DBD::CSV package.
306
307       The minimal set of files we have to implement are Makefile.PL, README,
308       MANIFEST and Driver.pm.
309
310   Pure Perl version of Makefile.PL
311       You typically start with writing Makefile.PL, a Makefile generator. The
312       contents of this file are described in detail in the
313       ExtUtils::MakeMaker man pages. It is definitely a good idea if you
314       start reading them. At least you should know about the variables
315       CONFIGURE, DEFINED, PM, DIR, EXE_FILES, INC, LIBS, LINKTYPE, NAME,
316       OPTIMIZE, PL_FILES, VERSION, VERSION_FROM, clean, depend, realclean
317       from the ExtUtils::MakeMaker man page: these are used in almost any
318       Makefile.PL.
319
320       Additionally read the section on Overriding MakeMaker Methods and the
321       descriptions of the distcheck, disttest and dist targets: They will
322       definitely be useful for you.
323
324       Of special importance for DBI drivers is the postamble method from the
325       ExtUtils::MM_Unix man page.
326
327       For Emacs users, I recommend the libscan method, which removes Emacs
328       backup files (file names which end with a tilde '~') from lists of
329       files.
330
331       Now an example, I use the word "Driver" wherever you should insert your
332       driver's name:
333
334         # -*- perl -*-
335
336         use ExtUtils::MakeMaker;
337
338         WriteMakefile(
339             dbd_edit_mm_attribs( {
340                 'NAME'         => 'DBD::Driver',
341                 'VERSION_FROM' => 'Driver.pm',
342                 'INC'          => '',
343                 'dist'         => { 'SUFFIX'   => '.gz',
344                                     'COMPRESS' => 'gzip -9f' },
345                 'realclean'    => { FILES => '*.xsi' },
346                 'PREREQ_PM'    => '1.03',
347                 'CONFIGURE'    => sub {
348                     eval {require DBI::DBD;};
349                     if ($@) {
350                         warn $@;
351                         exit 0;
352                     }
353                     my $dbi_arch_dir = dbd_dbi_arch_dir();
354                     if (exists($opts{INC})) {
355                         return {INC => "$opts{INC} -I$dbi_arch_dir"};
356                     } else {
357                         return {INC => "-I$dbi_arch_dir"};
358                     }
359                 }
360             },
361             { create_pp_tests => 1})
362         );
363
364         package MY;
365         sub postamble { return main::dbd_postamble(@_); }
366         sub libscan {
367             my ($self, $path) = @_;
368             ($path =~ m/\~$/) ? undef : $path;
369         }
370
371       Note the calls to "dbd_edit_mm_attribs()" and "dbd_postamble()".
372
373       The second hash reference in the call to "dbd_edit_mm_attribs()"
374       (containing "create_pp_tests()") is optional; you should not use it
375       unless your driver is a pure Perl driver (that is, it does not use C
376       and XS code). Therefore, the call to "dbd_edit_mm_attribs()" is not
377       relevant for C/XS drivers and may be omitted; simply use the (single)
378       hash reference containing NAME etc as the only argument to
379       "WriteMakefile()".
380
381       Note that the "dbd_edit_mm_attribs()" code will fail if you do not have
382       a t sub-directory containing at least one test case.
383
384       PREREQ_PM tells MakeMaker that DBI (version 1.03 in this case) is
385       required for this module. This will issue a warning that DBI 1.03 is
386       missing if someone attempts to install your DBD without DBI 1.03. See
387       CONFIGURE below for why this does not work reliably in stopping cpan
388       testers failing your module if DBI is not installed.
389
390       CONFIGURE is a subroutine called by MakeMaker during "WriteMakefile".
391       By putting the "require DBI::DBD" in this section we can attempt to
392       load DBI::DBD but if it is missing we exit with success. As we exit
393       successfully without creating a Makefile when DBI::DBD is missing cpan
394       testers will not report a failure. This may seem at odds with PREREQ_PM
395       but PREREQ_PM does not cause "WriteMakefile" to fail (unless you also
396       specify PREREQ_FATAL which is strongly discouraged by MakeMaker) so
397       "WriteMakefile" would continue to call "dbd_dbi_arch_dir" and fail.
398
399       All drivers must use "dbd_postamble()" or risk running into problems.
400
401       Note the specification of VERSION_FROM; the named file (Driver.pm) will
402       be scanned for the first line that looks like an assignment to
403       $VERSION, and the subsequent text will be used to determine the version
404       number.  Note the commentary in ExtUtils::MakeMaker on the subject of
405       correctly formatted version numbers.
406
407       If your driver depends upon external software (it usually will), you
408       will need to add code to ensure that your environment is workable
409       before the call to "WriteMakefile()". If you need to check for the
410       existence of an external library and perhaps modify INC to include the
411       paths to where the external library header files are located and you
412       cannot find the library or header files make sure you output a message
413       saying they cannot be found but "exit 0" (success) before calling
414       "WriteMakefile" or CPAN testers will fail your module if the external
415       library is not found.
416
417       A full-fledged Makefile.PL can be quite large (for example, the files
418       for DBD::Oracle and DBD::Informix are both over 1000 lines long, and
419       the Informix one uses - and creates - auxiliary modules too).
420
421       See also ExtUtils::MakeMaker and ExtUtils::MM_Unix. Consider using
422       CPAN::MakeMaker in place of ExtUtils::MakeMaker.
423
424   README
425       The README file should describe what the driver is for, the pre-
426       requisites for the build process, the actual build process, how to
427       report errors, and who to report them to.
428
429       Users will find ways of breaking the driver build and test process
430       which you would never even have dreamed to be possible in your worst
431       nightmares. Therefore, you need to write this document defensively,
432       precisely and concisely.
433
434       As always, use the README from one of the established drivers as a
435       basis for your own; the version in DBD::Informix is worth a look as it
436       has been quite successful in heading off problems.
437
438       ·   Note that users will have versions of Perl and DBI that are both
439           older and newer than you expected, but this will seldom cause much
440           trouble.  When it does, it will be because you are using features
441           of DBI that are not supported in the version they are using.
442
443       ·   Note that users will have versions of the database software that
444           are both older and newer than you expected. You will save yourself
445           time in the long run if you can identify the range of versions
446           which have been tested and warn about versions which are not known
447           to be OK.
448
449       ·   Note that many people trying to install your driver will not be
450           experts in the database software.
451
452       ·   Note that many people trying to install your driver will not be
453           experts in C or Perl.
454
455   MANIFEST
456       The MANIFEST will be used by the Makefile's dist target to build the
457       distribution tar file that is uploaded to CPAN. It should list every
458       file that you want to include in your distribution, one per line.
459
460   lib/Bundle/DBD/Driver.pm
461       The CPAN module provides an extremely powerful bundle mechanism that
462       allows you to specify pre-requisites for your driver.
463
464       The primary pre-requisite is Bundle::DBI; you may want or need to add
465       some more. With the bundle set up correctly, the user can type:
466
467               perl -MCPAN -e 'install Bundle::DBD::Driver'
468
469       and Perl will download, compile, test and install all the Perl modules
470       needed to build your driver.
471
472       The prerequisite modules are listed in the "CONTENTS" section, with the
473       official name of the module followed by a dash and an informal name or
474       description.
475
476       ·   Listing Bundle::DBI as the main pre-requisite simplifies life.
477
478       ·   Don't forget to list your driver.
479
480       ·   Note that unless the DBMS is itself a Perl module, you cannot list
481           it as a pre-requisite in this file.
482
483       ·   You should keep the version of the bundle the same as the version
484           of your driver.
485
486       ·   You should add configuration management, copyright, and licencing
487           information at the top.
488
489       A suitable skeleton for this file is shown below.
490
491         package Bundle::DBD::Driver;
492
493         $VERSION = '0.01';
494
495         1;
496
497         __END__
498
499         =head1 NAME
500
501         Bundle::DBD::Driver - A bundle to install all DBD::Driver related modules
502
503         =head1 SYNOPSIS
504
505         C<perl -MCPAN -e 'install Bundle::DBD::Driver'>
506
507         =head1 CONTENTS
508
509         Bundle::DBI  - Bundle for DBI by TIMB (Tim Bunce)
510
511         DBD::Driver  - DBD::Driver by YOU (Your Name)
512
513         =head1 DESCRIPTION
514
515         This bundle includes all the modules used by the Perl Database
516         Interface (DBI) driver for Driver (DBD::Driver), assuming the
517         use of DBI version 1.13 or later, created by Tim Bunce.
518
519         If you've not previously used the CPAN module to install any
520         bundles, you will be interrogated during its setup phase.
521         But when you've done it once, it remembers what you told it.
522         You could start by running:
523
524           C<perl -MCPAN -e 'install Bundle::CPAN'>
525
526         =head1 SEE ALSO
527
528         Bundle::DBI
529
530         =head1 AUTHOR
531
532         Your Name E<lt>F<you@yourdomain.com>E<gt>
533
534         =head1 THANKS
535
536         This bundle was created by ripping off Bundle::libnet created by
537         Graham Barr E<lt>F<gbarr@ti.com>E<gt>, and radically simplified
538         with some information from Jochen Wiedmann E<lt>F<joe@ispsoft.de>E<gt>.
539         The template was then included in the DBI::DBD documentation by
540         Jonathan Leffler E<lt>F<jleffler@informix.com>E<gt>.
541
542         =cut
543
544   lib/DBD/Driver/Summary.pm
545       There is no substitute for taking the summary file from a driver that
546       was documented in the Perl book (such as DBD::Oracle or DBD::Informix
547       or DBD::ODBC, to name but three), and adapting it to describe the
548       facilities available via DBD::Driver when accessing the Driver
549       database.
550
551   Pure Perl version of Driver.pm
552       The Driver.pm file defines the Perl module DBD::Driver for your driver.
553       It will define a package DBD::Driver along with some version
554       information, some variable definitions, and a function "driver()" which
555       will have a more or less standard structure.
556
557       It will also define three sub-packages of DBD::Driver:
558
559       DBD::Driver::dr
560           with methods "connect()", "data_sources()" and "disconnect_all()";
561
562       DBD::Driver::db
563           with methods such as "prepare()";
564
565       DBD::Driver::st
566           with methods such as "execute()" and "fetch()".
567
568       The Driver.pm file will also contain the documentation specific to
569       DBD::Driver in the format used by perldoc.
570
571       In a pure Perl driver, the Driver.pm file is the core of the
572       implementation. You will need to provide all the key methods needed by
573       DBI.
574
575       Now let's take a closer look at an excerpt of File.pm as an example.
576       We ignore things that are common to any module (even non-DBI modules)
577       or really specific to the DBD::File package.
578
579       The DBD::Driver package
580
581       The header
582
583         package DBD::File;
584
585         use strict;
586         use vars qw($VERSION $drh);
587
588         $VERSION = "1.23.00"  # Version number of DBD::File
589
590       This is where the version number of your driver is specified, and is
591       where Makefile.PL looks for this information. Please ensure that any
592       other modules added with your driver are also version stamped so that
593       CPAN does not get confused.
594
595       It is recommended that you use a two-part (1.23) or three-part
596       (1.23.45) version number. Also consider the CPAN system, which gets
597       confused and considers version 1.10 to precede version 1.9, so that
598       using a raw CVS, RCS or SCCS version number is probably not appropriate
599       (despite being very common).
600
601       For Subversion you could use:
602
603         $VERSION = sprintf("12.%06d", q$Revision: 12345 $ =~ /(\d+)/o);
604
605       (use lots of leading zeros on the second portion so if you move the
606       code to a shared repository like svn.perl.org the much larger revision
607       numbers won't cause a problem, at least not for a few years).  For RCS
608       or CVS you can use:
609
610         $VERSION = sprintf "%d.%02d", '$Revision: 11.21 $ ' =~ /(\d+)\.(\d+)/;
611
612       which pads out the fractional part with leading zeros so all is well
613       (so long as you don't go past x.99)
614
615         $drh = undef;         # holds driver handle once initialized
616
617       This is where the driver handle will be stored, once created.  Note
618       that you may assume there is only one handle for your driver.
619
620       The driver constructor
621
622       The "driver()" method is the driver handle constructor. Note that the
623       "driver()" method is in the DBD::Driver package, not in one of the sub-
624       packages DBD::Driver::dr, DBD::Driver::db, or DBD::Driver::db.
625
626         sub driver
627         {
628             return $drh if $drh;      # already created - return same one
629             my ($class, $attr) = @_;
630
631             $class .= "::dr";
632
633             DBD::Driver::db->install_method('drv_example_dbh_method');
634             DBD::Driver::st->install_method('drv_example_sth_method');
635
636             # not a 'my' since we use it above to prevent multiple drivers
637             $drh = DBI::_new_drh($class, {
638                     'Name'        => 'File',
639                     'Version'     => $VERSION,
640                     'Attribution' => 'DBD::File by Jochen Wiedmann',
641                 })
642                 or return undef;
643
644             return $drh;
645         }
646
647       This is a reasonable example of how DBI implements its handles. There
648       are three kinds: driver handles (typically stored in $drh; from now on
649       called drh or $drh), database handles (from now on called dbh or $dbh)
650       and statement handles (from now on called sth or $sth).
651
652       The prototype of "DBI::_new_drh()" is
653
654         $drh = DBI::_new_drh($class, $public_attrs, $private_attrs);
655
656       with the following arguments:
657
658       $class
659           is typically the class for your driver, (for example,
660           "DBD::File::dr"), passed as the first argument to the "driver()"
661           method.
662
663       $public_attrs
664           is a hash ref to attributes like Name, Version, and Attribution.
665           These are processed and used by DBI. You had better not make any
666           assumptions about them nor should you add private attributes here.
667
668       $private_attrs
669           This is another (optional) hash ref with your private attributes.
670           DBI will store them and otherwise leave them alone.
671
672       The "DBI::_new_drh()" method and the "driver()" method both return
673       "undef" for failure (in which case you must look at $DBI::err and
674       $DBI::errstr for the failure information, because you have no driver
675       handle to use).
676
677       Using install_method() to expose driver-private methods
678
679           DBD::Foo::db->install_method($method_name, \%attr);
680
681       Installs the driver-private method named by $method_name into the DBI
682       method dispatcher so it can be called directly, avoiding the need to
683       use the func() method.
684
685       It is called as a static method on the driver class to which the method
686       belongs. The method name must begin with the corresponding registered
687       driver-private prefix. For example, for DBD::Oracle $method_name must
688       being with '"ora_"', and for DBD::AnyData it must begin with '"ad_"'.
689
690       The "\%attr" attributes can be used to provide fine control over how
691       the DBI dispatcher handles the dispatching of the method. However it's
692       undocumented at the moment. See the IMA_* #define's in DBI.xs and the
693       O=>0x000x values in the initialization of %DBI::DBI_methods in DBI.pm.
694       (Volunteers to polish up and document the interface are very welcome to
695       get in touch 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_xsh.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_DBISTATE(imp_xxh)"
1836       macro.
1837
1838       The name "DBILOGFP", which was also used in previous versions of this
1839       document, should be replaced by "DBIc_LOGPIO(imp_xxh)".
1840
1841       Your code should not call the C "<stdio.h>" I/O functions; you should
1842       use "PerlIO_printf()" as shown:
1843
1844             if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
1845                 PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar %s: %s\n",
1846                     foo, neatsvpv(errstr,0));
1847
1848       That's the first time we see how tracing works within a DBI driver.
1849       Make use of this as often as you can, but don't output anything at a
1850       trace level less than 3. Levels 1 and 2 are reserved for the DBI.
1851
1852       You can define up to 8 private trace flags using the top 8 bits of
1853       "DBIc_TRACE_FLAGS(imp)", that is: 0xFF000000. See the
1854       "parse_trace_flag()" method elsewhere in this document.
1855
1856       The dbd_dr_data_sources method
1857
1858       This method is optional; the support for it was added in DBI v1.33.
1859
1860       As noted in the discussion of Driver.pm, if the data sources can be
1861       determined by pure Perl code, do it that way. If, as in DBD::Informix,
1862       the information is obtained by a C function call, then you need to
1863       define a function that matches the prototype:
1864
1865         extern AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attrs);
1866
1867       An outline implementation for DBD::Informix follows, assuming that the
1868       "sqgetdbs()" function call shown will return up to 100 databases names,
1869       with the pointers to each name in the array dbsname and the name
1870       strings themselves being stores in dbsarea.
1871
1872         AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr)
1873         {
1874             int ndbs;
1875             int i;
1876             char *dbsname[100];
1877             char  dbsarea[10000];
1878             AV *av = Nullav;
1879
1880             if (sqgetdbs(&ndbs, dbsname, 100, dbsarea, sizeof(dbsarea)) == 0)
1881             {
1882                 av = NewAV();
1883                 av_extend(av, (I32)ndbs);
1884                 sv_2mortal((SV *)av);
1885                 for (i = 0; i < ndbs; i++)
1886                   av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i]));
1887             }
1888             return(av);
1889         }
1890
1891       The actual DBD::Informix implementation has a number of extra lines of
1892       code, logs function entry and exit, reports the error from
1893       "sqgetdbs()", and uses "#define"'d constants for the array sizes.
1894
1895       The dbd_db_login6 method
1896
1897         int dbd_db_login6_sv(SV* dbh, imp_dbh_t* imp_dbh, SV* dbname,
1898                              SV* user, SV* auth, SV *attr);
1899
1900         or
1901
1902         int dbd_db_login6(SV* dbh, imp_dbh_t* imp_dbh, char* dbname,
1903                          char* user, char* auth, SV *attr);
1904
1905       This function will really connect to the database. The argument dbh is
1906       the database handle. imp_dbh is the pointer to the handles private
1907       data, as is imp_xxx in "dbd_drv_error()" above. The arguments dbname,
1908       user, auth and attr correspond to the arguments of the driver handle's
1909       "connect()" method.
1910
1911       You will quite often use database specific attributes here, that are
1912       specified in the DSN. I recommend you parse the DSN (using Perl) within
1913       the "connect()" method and pass the segments of the DSN via the
1914       attributes parameter through "_login()" to "dbd_db_login6()".
1915
1916       Here's how you fetch them; as an example we use hostname attribute,
1917       which can be up to 12 characters long excluding null terminator:
1918
1919         SV** svp;
1920         STRLEN len;
1921         char* hostname;
1922
1923         if ( (svp = DBD_ATTRIB_GET_SVP(attr, "drv_hostname", 12)) && SvTRUE(*svp)) {
1924             hostname = SvPV(*svp, len);
1925             DBD_ATTRIB_DELETE(attr, "drv_hostname", 12); /* avoid later STORE */
1926         } else {
1927             hostname = "localhost";
1928         }
1929
1930       If you handle any driver specific attributes in the dbd_db_login6
1931       method you probably want to delete them from "attr" (as above with
1932       DBD_ATTRIB_DELETE). If you don't delete your handled attributes DBI
1933       will call "STORE" for each attribute after the connect/login and this
1934       is at best redundant for attributes you have already processed.
1935
1936       Note: Until revision 11605 (post DBI 1.607), there was a problem with
1937       DBD_ATTRIBUTE_DELETE so unless you require a DBI version after 1.607
1938       you need to replace each DBD_ATTRIBUTE_DELETE call with:
1939
1940         hv_delete((HV*)SvRV(attr), key, key_len, G_DISCARD)
1941
1942       Note that you can also obtain standard attributes such as AutoCommit
1943       and ChopBlanks from the attributes parameter, using "DBD_ATTRIB_GET_IV"
1944       for integer attributes.
1945
1946       If, for example, your database does not support transactions but
1947       AutoCommit is set off (requesting transaction support), then you can
1948       emulate a 'failure to connect'.
1949
1950       Now you should really connect to the database. In general, if the
1951       connection fails, it is best to ensure that all allocated resources are
1952       released so that the handle does not need to be destroyed separately.
1953       If you are successful (and possibly even if you fail but you have
1954       allocated some resources), you should use the following macros:
1955
1956         DBIc_IMPSET_on(imp_dbh);
1957
1958       This indicates that the driver (implementor) has allocated resources in
1959       the imp_dbh structure and that the implementors private
1960       "dbd_db_destroy()" function should be called when the handle is
1961       destroyed.
1962
1963         DBIc_ACTIVE_on(imp_dbh);
1964
1965       This indicates that the handle has an active connection to the server
1966       and that the "dbd_db_disconnect()" function should be called before the
1967       handle is destroyed.
1968
1969       Note that if you do need to fail, you should report errors via the drh
1970       or imp_drh rather than via dbh or imp_dbh because imp_dbh will be
1971       destroyed by the failure, so errors recorded in that handle will not be
1972       visible to DBI, and hence not the user either.
1973
1974       Note too, that the function is passed dbh and imp_dbh, and there is a
1975       macro "D_imp_drh_from_dbh" which can recover the imp_drh from the
1976       imp_dbh. However, there is no DBI macro to provide you with the drh
1977       given either the imp_dbh or the dbh or the imp_drh (and there's no way
1978       to recover the dbh given just the imp_dbh).
1979
1980       This suggests that, despite the above notes about "dbd_drv_error()"
1981       taking an "SV *", it may be better to have two error routines, one
1982       taking imp_dbh and one taking imp_drh instead. With care, you can
1983       factor most of the formatting code out so that these are small routines
1984       calling a common error formatter. See the code in DBD::Informix 1.05.00
1985       for more information.
1986
1987       The "dbd_db_login6()" function should return TRUE for success, FALSE
1988       otherwise.
1989
1990       Drivers implemented long ago may define the five-argument function
1991       "dbd_db_login()" instead of "dbd_db_login6()". The missing argument is
1992       the attributes. There are ways to work around the missing attributes,
1993       but they are ungainly; it is much better to use the 6-argument form.
1994       Even later drivers will use "dbd_db_login6_sv()" which provides the
1995       dbname, username and password as SVs.
1996
1997       The dbd_db_commit and dbd_db_rollback methods
1998
1999         int dbd_db_commit(SV *dbh, imp_dbh_t *imp_dbh);
2000         int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh);
2001
2002       These are used for commit and rollback. They should return TRUE for
2003       success, FALSE for error.
2004
2005       The arguments dbh and imp_dbh are the same as for "dbd_db_login6()"
2006       above; I will omit describing them in what follows, as they appear
2007       always.
2008
2009       These functions should return TRUE for success, FALSE otherwise.
2010
2011       The dbd_db_disconnect method
2012
2013       This is your private part of the "disconnect()" method. Any dbh with
2014       the ACTIVE flag on must be disconnected. (Note that you have to set it
2015       in "dbd_db_connect()" above.)
2016
2017         int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh);
2018
2019       The database handle will return TRUE for success, FALSE otherwise.  In
2020       any case it should do a:
2021
2022         DBIc_ACTIVE_off(imp_dbh);
2023
2024       before returning so DBI knows that "dbd_db_disconnect()" was executed.
2025
2026       Note that there's nothing to stop a dbh being disconnected while it
2027       still have active children. If your database API reacts badly to trying
2028       to use an sth in this situation then you'll need to add code like this
2029       to all sth methods:
2030
2031         if (!DBIc_ACTIVE(DBIc_PARENT_COM(imp_sth)))
2032           return 0;
2033
2034       Alternatively, you can add code to your driver to keep explicit track
2035       of the statement handles that exist for each database handle and
2036       arrange to destroy those handles before disconnecting from the
2037       database. There is code to do this in DBD::Informix. Similar comments
2038       apply to the driver handle keeping track of all the database handles.
2039
2040       Note that the code which destroys the subordinate handles should only
2041       release the associated database resources and mark the handles
2042       inactive; it does not attempt to free the actual handle structures.
2043
2044       This function should return TRUE for success, FALSE otherwise, but it
2045       is not clear what anything can do about a failure.
2046
2047       The dbd_db_discon_all method
2048
2049         int dbd_discon_all (SV *drh, imp_drh_t *imp_drh);
2050
2051       This function may be called at shutdown time. It should make best-
2052       efforts to disconnect all database handles - if possible. Some
2053       databases don't support that, in which case you can do nothing but
2054       return 'success'.
2055
2056       This function should return TRUE for success, FALSE otherwise, but it
2057       is not clear what anything can do about a failure.
2058
2059       The dbd_db_destroy method
2060
2061       This is your private part of the database handle destructor. Any dbh
2062       with the IMPSET flag on must be destroyed, so that you can safely free
2063       resources. (Note that you have to set it in "dbd_db_connect()" above.)
2064
2065         void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh)
2066         {
2067             DBIc_IMPSET_off(imp_dbh);
2068         }
2069
2070       The DBI Driver.xst code will have called "dbd_db_disconnect()" for you,
2071       if the handle is still 'active', before calling "dbd_db_destroy()".
2072
2073       Before returning the function must switch IMPSET to off, so DBI knows
2074       that the destructor was called.
2075
2076       A DBI handle doesn't keep references to its children. But children do
2077       keep references to their parents. So a database handle won't be
2078       "DESTROY"'d until all its children have been "DESTROY"'d.
2079
2080       The dbd_db_STORE_attrib method
2081
2082       This function handles
2083
2084         $dbh->{$key} = $value;
2085
2086       Its prototype is:
2087
2088         int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv,
2089                                 SV* valuesv);
2090
2091       You do not handle all attributes; on the contrary, you should not
2092       handle DBI attributes here: leave this to DBI. (There are two
2093       exceptions, AutoCommit and ChopBlanks, which you should care about.)
2094
2095       The return value is TRUE if you have handled the attribute or FALSE
2096       otherwise. If you are handling an attribute and something fails, you
2097       should call "dbd_drv_error()", so DBI can raise exceptions, if desired.
2098       If "dbd_drv_error()" returns, however, you have a problem: the user
2099       will never know about the error, because he typically will not check
2100       "$dbh->errstr()".
2101
2102       I cannot recommend a general way of going on, if "dbd_drv_error()"
2103       returns, but there are examples where even the DBI specification
2104       expects that you "croak()". (See the AutoCommit method in DBI.)
2105
2106       If you have to store attributes, you should either use your private
2107       data structure imp_xxx, the handle hash (via "(HV*)SvRV(dbh)"), or use
2108       the private imp_data.
2109
2110       The first is best for internal C values like integers or pointers and
2111       where speed is important within the driver. The handle hash is best for
2112       values the user may want to get/set via driver-specific attributes.
2113       The private imp_data is an additional "SV" attached to the handle. You
2114       could think of it as an unnamed handle attribute. It's not normally
2115       used.
2116
2117       The dbd_db_FETCH_attrib method
2118
2119       This is the counterpart of "dbd_db_STORE_attrib()", needed for:
2120
2121         $value = $dbh->{$key};
2122
2123       Its prototype is:
2124
2125         SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv);
2126
2127       Unlike all previous methods this returns an "SV" with the value. Note
2128       that you should normally execute "sv_2mortal()", if you return a
2129       nonconstant value. (Constant values are &sv_undef, &sv_no and &sv_yes.)
2130
2131       Note, that DBI implements a caching algorithm for attribute values.  If
2132       you think, that an attribute may be fetched, you store it in the dbh
2133       itself:
2134
2135         if (cacheit) /* cache value for later DBI 'quick' fetch? */
2136             hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
2137
2138       The dbd_st_prepare method
2139
2140       This is the private part of the "prepare()" method. Note that you must
2141       not really execute the statement here. You may, however, preparse and
2142       validate the statement, or do similar things.
2143
2144         int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement,
2145                            SV* attribs);
2146
2147       A typical, simple, possibility is to do nothing and rely on the perl
2148       "prepare()" code that set the Statement attribute on the handle. This
2149       attribute can then be used by "dbd_st_execute()".
2150
2151       If the driver supports placeholders then the NUM_OF_PARAMS attribute
2152       must be set correctly by "dbd_st_prepare()":
2153
2154         DBIc_NUM_PARAMS(imp_sth) = ...
2155
2156       If you can, you should also setup attributes like NUM_OF_FIELDS, NAME,
2157       etc. here, but DBI doesn't require that - they can be deferred until
2158       execute() is called. However, if you do, document it.
2159
2160       In any case you should set the IMPSET flag, as you did in
2161       "dbd_db_connect()" above:
2162
2163         DBIc_IMPSET_on(imp_sth);
2164
2165       The dbd_st_execute method
2166
2167       This is where a statement will really be executed.
2168
2169         int dbd_st_execute(SV* sth, imp_sth_t* imp_sth);
2170
2171       "dbd_st_execute" should return -2 for any error, -1 if the number of
2172       rows affected is unknown else it should be the number of affected
2173       (updated, inserted) rows.
2174
2175       Note that you must be aware a statement may be executed repeatedly.
2176       Also, you should not expect that "finish()" will be called between two
2177       executions, so you might need code, like the following, near the start
2178       of the function:
2179
2180         if (DBIc_ACTIVE(imp_sth))
2181             dbd_st_finish(h, imp_sth);
2182
2183       If your driver supports the binding of parameters (it should!), but the
2184       database doesn't, you must do it here. This can be done as follows:
2185
2186         SV *svp;
2187         char* statement = DBD_ATTRIB_GET_PV(h, "Statement", 9, svp, "");
2188         int numParam = DBIc_NUM_PARAMS(imp_sth);
2189         int i;
2190
2191         for (i = 0; i < numParam; i++)
2192         {
2193             char* value = dbd_db_get_param(sth, imp_sth, i);
2194             /* It is your drivers task to implement dbd_db_get_param,    */
2195             /* it must be setup as a counterpart of dbd_bind_ph.         */
2196             /* Look for '?' and replace it with 'value'.  Difficult      */
2197             /* task, note that you may have question marks inside        */
2198             /* quotes and comments the like ...  :-(                     */
2199             /* See DBD::mysql for an example. (Don't look too deep into  */
2200             /* the example, you will notice where I was lazy ...)        */
2201         }
2202
2203       The next thing is to really execute the statement.
2204
2205       Note that you must set the attributes NUM_OF_FIELDS, NAME, etc when the
2206       statement is successfully executed if the driver has not already done
2207       so: they may be used even before a potential "fetchrow()".  In
2208       particular you have to tell DBI the number of fields that the statement
2209       has, because it will be used by DBI internally. Thus the function will
2210       typically ends with:
2211
2212         if (isSelectStatement) {
2213             DBIc_NUM_FIELDS(imp_sth) = numFields;
2214             DBIc_ACTIVE_on(imp_sth);
2215         }
2216
2217       It is important that the ACTIVE flag only be set for "SELECT"
2218       statements (or any other statements that can return many values from
2219       the database using a cursor-like mechanism). See "dbd_db_connect()"
2220       above for more explanations.
2221
2222       There plans for a preparse function to be provided by DBI, but this has
2223       not reached fruition yet.  Meantime, if you want to know how ugly it
2224       can get, try looking at the "dbd_ix_preparse()" in DBD::Informix
2225       dbdimp.ec and the related functions in iustoken.c and sqltoken.c.
2226
2227       The dbd_st_fetch method
2228
2229       This function fetches a row of data. The row is stored in in an array,
2230       of "SV"'s that DBI prepares for you. This has two advantages: it is
2231       fast (you even reuse the "SV"'s, so they don't have to be created after
2232       the first "fetchrow()"), and it guarantees that DBI handles
2233       "bind_cols()" for you.
2234
2235       What you do is the following:
2236
2237         AV* av;
2238         int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS
2239             is constant for this statement. There are drivers where this is
2240             not the case! */
2241         int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
2242         int i;
2243
2244         if (!fetch_new_row_of_data(...)) {
2245             ... /* check for error or end-of-data */
2246             DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */
2247             return Nullav;
2248         }
2249         /* get the fbav (field buffer array value) for this row       */
2250         /* it is very important to only call this after you know      */
2251         /* that you have a row of data to return.                     */
2252         av = DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
2253         for (i = 0; i < numFields; i++) {
2254             SV* sv = fetch_a_field(..., i);
2255             if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) {
2256                 /*  Remove white space from end (only) of sv  */
2257             }
2258             sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */
2259         }
2260         return av;
2261
2262       There's no need to use a "fetch_a_field()" function returning an "SV*".
2263       It's more common to use your database API functions to fetch the data
2264       as character strings and use code like this:
2265
2266         sv_setpvn(AvARRAY(av)[i], char_ptr, char_count);
2267
2268       "NULL" values must be returned as "undef". You can use code like this:
2269
2270         SvOK_off(AvARRAY(av)[i]);
2271
2272       The function returns the "AV" prepared by DBI for success or "Nullav"
2273       otherwise.
2274
2275        *FIX ME* Discuss what happens when there's no more data to fetch.
2276        Are errors permitted if another fetch occurs after the first fetch
2277        that reports no more data. (Permitted, not required.)
2278
2279       If an error occurs which leaves the $sth in a state where remaining
2280       rows can't be fetched then Active should be turned off before the
2281       method returns.
2282
2283       The dbd_st_finish3 method
2284
2285       The "$sth->finish()" method can be called if the user wishes to
2286       indicate that no more rows will be fetched even if the database has
2287       more rows to offer, and the DBI code can call the function when handles
2288       are being destroyed. See the DBI specification for more background
2289       details.
2290
2291       In both circumstances, the DBI code ends up calling the
2292       "dbd_st_finish3()" method (if you provide a mapping for
2293       "dbd_st_finish3()" in dbdimp.h), or "dbd_st_finish()" otherwise.  The
2294       difference is that "dbd_st_finish3()" takes a third argument which is
2295       an "int" with the value 1 if it is being called from a "destroy()"
2296       method and 0 otherwise.
2297
2298       Note that DBI v1.32 and earlier test on "dbd_db_finish3()" to call
2299       "dbd_st_finish3()"; if you provide "dbd_st_finish3()", either define
2300       "dbd_db_finish3()" too, or insist on DBI v1.33 or later.
2301
2302       All it needs to do is turn off the Active flag for the sth.  It will
2303       only be called by Driver.xst code, if the driver has set ACTIVE to on
2304       for the sth.
2305
2306       Outline example:
2307
2308         int dbd_st_finish3(SV* sth, imp_sth_t* imp_sth, int from_destroy) {
2309             if (DBIc_ACTIVE(imp_sth))
2310             {
2311                 /* close cursor or equivalent action */
2312                 DBIc_ACTIVE_off(imp_sth);
2313             }
2314             return 1;
2315         }
2316
2317       The from_destroy parameter is true if "dbd_st_finish3()" is being
2318       called from "DESTROY()" - and so the statement is about to be
2319       destroyed.  For many drivers there is no point in doing anything more
2320       than turning off the Active flag in this case.
2321
2322       The function returns TRUE for success, FALSE otherwise, but there isn't
2323       a lot anyone can do to recover if there is an error.
2324
2325       The dbd_st_destroy method
2326
2327       This function is the private part of the statement handle destructor.
2328
2329         void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth) {
2330             ... /* any clean-up that's needed */
2331             DBIc_IMPSET_off(imp_sth); /* let DBI know we've done it   */
2332         }
2333
2334       The DBI Driver.xst code will call "dbd_st_finish()" for you, if the sth
2335       has the ACTIVE flag set, before calling "dbd_st_destroy()".
2336
2337       The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods
2338
2339       These functions correspond to "dbd_db_STORE()" and "dbd_db_FETCH()"
2340       attrib above, except that they are for statement handles.  See above.
2341
2342         int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv,
2343                                 SV* valuesv);
2344         SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv);
2345
2346       The dbd_bind_ph method
2347
2348       This function is internally used by the "bind_param()" method, the
2349       "bind_param_inout()" method and by the DBI Driver.xst code if
2350       "execute()" is called with any bind parameters.
2351
2352         int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param,
2353                          SV *value, IV sql_type, SV *attribs,
2354                          int is_inout, IV maxlen);
2355
2356       The param argument holds an "IV" with the parameter number (1, 2, ...).
2357       The value argument is the parameter value and sql_type is its type.
2358
2359       If your driver does not support "bind_param_inout()" then you should
2360       ignore maxlen and croak if is_inout is TRUE.
2361
2362       If your driver does support "bind_param_inout()" then you should note
2363       that value is the "SV" after dereferencing the reference passed to
2364       "bind_param_inout()".
2365
2366       In drivers of simple databases the function will, for example, store
2367       the value in a parameter array and use it later in "dbd_st_execute()".
2368       See the DBD::mysql driver for an example.
2369
2370       Implementing bind_param_inout support
2371
2372       To provide support for parameters bound by reference rather than by
2373       value, the driver must do a number of things.  First, and most
2374       importantly, it must note the references and stash them in its own
2375       driver structure.  Secondly, when a value is bound to a column, the
2376       driver must discard any previous reference bound to the column.  On
2377       each execute, the driver must evaluate the references and internally
2378       bind the values resulting from the references.  This is only applicable
2379       if the user writes:
2380
2381         $sth->execute;
2382
2383       If the user writes:
2384
2385         $sth->execute(@values);
2386
2387       then DBI automatically calls the binding code for each element of
2388       @values.  These calls are indistinguishable from explicit user calls to
2389       "bind_param()".
2390
2391   C/XS version of Makefile.PL
2392       The Makefile.PL file for a C/XS driver is similar to the code needed
2393       for a pure Perl driver, but there are a number of extra bits of
2394       information needed by the build system.
2395
2396       For example, the attributes list passed to "WriteMakefile()" needs to
2397       specify the object files that need to be compiled and built into the
2398       shared object (DLL). This is often, but not necessarily, just dbdimp.o
2399       (unless that should be dbdimp.obj because you're building on MS
2400       Windows).
2401
2402       Note that you can reliably determine the extension of the object files
2403       from the $Config{obj_ext} values, and there are many other useful
2404       pieces of configuration information lurking in that hash.  You get
2405       access to it with:
2406
2407           use Config;
2408
2409   Methods which do not need to be written
2410       The DBI code implements the majority of the methods which are accessed
2411       using the notation "DBI->function()", the only exceptions being
2412       "DBI->connect()" and "DBI->data_sources()" which require support from
2413       the driver.
2414
2415       The DBI code implements the following documented driver, database and
2416       statement functions which do not need to be written by the DBD driver
2417       writer.
2418
2419       $dbh->do()
2420           The default implementation of this function prepares, executes and
2421           destroys the statement.  This can be replaced if there is a better
2422           way to implement this, such as "EXECUTE IMMEDIATE" which can
2423           sometimes be used if there are no parameters.
2424
2425       $h->errstr()
2426       $h->err()
2427       $h->state()
2428       $h->trace()
2429           The DBD driver does not need to worry about these routines at all.
2430
2431       $h->{ChopBlanks}
2432           This attribute needs to be honored during "fetch()" operations, but
2433           does not need to be handled by the attribute handling code.
2434
2435       $h->{RaiseError}
2436           The DBD driver does not need to worry about this attribute at all.
2437
2438       $h->{PrintError}
2439           The DBD driver does not need to worry about this attribute at all.
2440
2441       $sth->bind_col()
2442           Assuming the driver uses the "DBIc_DBISTATE(imp_xxh)->get_fbav()"
2443           function (C drivers, see below), or the "$sth->_set_fbav($data)"
2444           method (Perl drivers) the driver does not need to do anything about
2445           this routine.
2446
2447       $sth->bind_columns()
2448           Regardless of whether the driver uses
2449           "DBIc_DBISTATE(imp_xxh)->get_fbav()", the driver does not need to
2450           do anything about this routine as it simply iteratively calls
2451           "$sth->bind_col()".
2452
2453       The DBI code implements a default implementation of the following
2454       functions which do not need to be written by the DBD driver writer
2455       unless the default implementation is incorrect for the Driver.
2456
2457       $dbh->quote()
2458           This should only be written if the database does not accept the
2459           ANSI SQL standard for quoting strings, with the string enclosed in
2460           single quotes and any embedded single quotes replaced by two
2461           consecutive single quotes.
2462
2463           For the two argument form of quote, you need to implement the
2464           "type_info()" method to provide the information that quote needs.
2465
2466       $dbh->ping()
2467           This should be implemented as a simple efficient way to determine
2468           whether the connection to the database is still alive. Typically
2469           code like this:
2470
2471             sub ping {
2472                 my $dbh = shift;
2473                 $sth = $dbh->prepare_cached(q{
2474                     select * from A_TABLE_NAME where 1=0
2475                 }) or return 0;
2476                 $sth->execute or return 0;
2477                 $sth->finish;
2478                 return 1;
2479             }
2480
2481           where A_TABLE_NAME is the name of a table that always exists (such
2482           as a database system catalogue).
2483
2484       $drh->default_user
2485           The default implementation of default_user will get the database
2486           username and password fields from $ENV{DBI_USER} and
2487           $ENV{DBI_PASS}. You can override this method. It is called as
2488           follows:
2489
2490             ($user, $pass) = $drh->default_user($user, $pass, $attr)
2491

METADATA METHODS

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

TRACING

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

WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE

2818       Study Oraperl.pm (supplied with DBD::Oracle) and Ingperl.pm (supplied
2819       with DBD::Ingres) and the corresponding dbdimp.c files for ideas.
2820
2821       Note that the emulation code sets "$dbh->{CompatMode} = 1;" for each
2822       connection so that the internals of the driver can implement behaviour
2823       compatible with the old interface when dealing with those handles.
2824
2825   Setting emulation perl variables
2826       For example, ingperl has a $sql_rowcount variable. Rather than try to
2827       manually update this in Ingperl.pm it can be done faster in C code.  In
2828       "dbd_init()":
2829
2830         sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI);
2831
2832       In the relevant places do:
2833
2834         if (DBIc_COMPAT(imp_sth))     /* only do this for compatibility mode handles */
2835             sv_setiv(sql_rowcount, the_row_count);
2836

OTHER MISCELLANEOUS INFORMATION

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

SUBCLASSING DBI DRIVERS

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

AUTHORS

3043       Jonathan Leffler <jleffler@us.ibm.com> (previously
3044       <jleffler@informix.com>), Jochen Wiedmann <joe@ispsoft.de>, Steffen
3045       Goeldner <sgoeldner@cpan.org>, and Tim Bunce <dbi-users@perl.org>.
3046
3047
3048
3049perl v5.16.3                      2013-04-04                       DBI::DBD(3)
Impressum