.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "DBI::DBD 3pm" .TH DBI::DBD 3pm 2024-03-07 "perl v5.38.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME DBI::DBD \- Perl DBI Database Driver Writer's Guide .SH SYNOPSIS .IX Header "SYNOPSIS" .Vb 1 \& perldoc DBI::DBD .Ve .SS "Version and volatility" .IX Subsection "Version and volatility" This document is \fIstill\fR a minimal draft which is in need of further work. .PP Please read the \fBDBI\fR documentation first and fully. Then look at the implementation of some high-profile and regularly maintained drivers like DBD::Oracle, DBD::ODBC, DBD::Pg etc. (Those are no no particular order.) .PP Then reread the \fBDBI\fR specification and the code of those drivers again as you're reading this. It'll help. Where this document and the driver code differ it's likely that the driver code is more correct, especially if multiple drivers do the same thing. .PP This document is a patchwork of contributions from various authors. More contributions (preferably as patches) are very welcome. .SH DESCRIPTION .IX Header "DESCRIPTION" This document is primarily intended to help people writing new database drivers for the Perl Database Interface (Perl DBI). It may also help others interested in discovering why the internals of a \fBDBD\fR driver are written the way they are. .PP This is a guide. Few (if any) of the statements in it are completely authoritative under all possible circumstances. This means you will need to use judgement in applying the guidelines in this document. If in \fIany\fR doubt at all, please do contact the \fIdbi-dev\fR mailing list (details given below) where Tim Bunce and other driver authors can help. .SH "CREATING A NEW DRIVER" .IX Header "CREATING A NEW DRIVER" The first rule for creating a new database driver for the Perl DBI is very simple: \fBDON'T!\fR .PP There is usually a driver already available for the database you want to use, almost regardless of which database you choose. Very often, the database will provide an ODBC driver interface, so you can often use \&\fBDBD::ODBC\fR to access the database. This is typically less convenient on a Unix box than on a Microsoft Windows box, but there are numerous options for ODBC driver managers on Unix too, and very often the ODBC driver is provided by the database supplier. .PP Before deciding that you need to write a driver, do your homework to ensure that you are not wasting your energies. .PP [As of December 2002, the consensus is that if you need an ODBC driver manager on Unix, then the unixODBC driver (available from ) is the way to go.] .PP The second rule for creating a new database driver for the Perl DBI is also very simple: \fBDon't \-\- get someone else to do it for you!\fR .PP Nevertheless, there are occasions when it is necessary to write a new driver, often to use a proprietary language or API to access the database more swiftly, or more comprehensively, than an ODBC driver can. Then you should read this document very carefully, but with a suitably sceptical eye. .PP If there is something in here that does not make any sense, question it. You might be right that the information is bogus, but don't come to that conclusion too quickly. .SS "URLs and mailing lists" .IX Subsection "URLs and mailing lists" The primary web-site for locating \fBDBI\fR software and information is .PP .Vb 1 \& http://dbi.perl.org/ .Ve .PP There are two main and one auxiliary mailing lists for people working with \fBDBI\fR. The primary lists are \fIdbi\-users@perl.org\fR for general users of \fBDBI\fR and \fBDBD\fR drivers, and \fIdbi\-dev@perl.org\fR mainly for \fBDBD\fR driver writers (don't join the \fIdbi-dev\fR list unless you have a good reason). The auxiliary list is \fIdbi\-announce@perl.org\fR for announcing new releases of \fBDBI\fR or \fBDBD\fR drivers. .PP You can join these lists by accessing the web-site . The lists are closed so you cannot send email to any of the lists unless you join the list first. .PP You should also consider monitoring the \fIcomp.lang.perl.*\fR newsgroups, especially \fIcomp.lang.perl.modules\fR. .SS "The Cheetah book" .IX Subsection "The Cheetah book" The definitive book on Perl DBI is the Cheetah book, so called because of the picture on the cover. Its proper title is '\fIProgramming the Perl DBI: Database programming with Perl\fR' by Alligator Descartes and Tim Bunce, published by O'Reilly Associates, February 2000, ISBN 1\-56592\-699\-4. Buy it now if you have not already done so, and read it. .SS "Locating drivers" .IX Subsection "Locating drivers" Before writing a new driver, it is in your interests to find out whether there already is a driver for your database. If there is such a driver, it would be much easier to make use of it than to write your own! .PP The primary web-site for locating Perl software is . You should look under the various modules listings for the software you are after. For example: .PP .Vb 1 \& http://search.cpan.org/modlist/Database_Interfaces .Ve .PP Follow the \fBDBD::\fR and \fBDBIx::\fR links at the top to see those subsets. .PP See the \fBDBI\fR docs for information on \fBDBI\fR web sites and mailing lists. .SS "Registering a new driver" .IX Subsection "Registering a new driver" Before going through any official registration process, you will need to establish that there is no driver already in the works. You'll do that by asking the \fBDBI\fR mailing lists whether there is such a driver available, or whether anybody is working on one. .PP When you get the go ahead, you will need to establish the name of the driver and a prefix for the driver. Typically, the name is based on the name of the database software it uses, and the prefix is a contraction of that. Hence, \fBDBD::Oracle\fR has the name \fIOracle\fR and the prefix \&'\fIora_\fR'. The prefix must be lowercase and contain no underscores other than the one at the end. .PP This information will be recorded in the \fBDBI\fR module. Apart from documentation purposes, registration is a prerequisite for installing private methods. .PP If you are writing a driver which will not be distributed on CPAN, then you should choose a prefix beginning with '\fIx_\fR', to avoid potential prefix collisions with drivers registered in the future. Thus, if you wrote a non-CPAN distributed driver called \fBDBD::CustomDB\fR, the prefix might be '\fIx_cdb_\fR'. .PP This document assumes you are writing a driver called \fBDBD::Driver\fR, and that the prefix '\fIdrv_\fR' is assigned to the driver. .SS "Two styles of database driver" .IX Subsection "Two styles of database driver" There are two distinct styles of database driver that can be written to work with the Perl DBI. .PP Your driver can be written in pure Perl, requiring no C compiler. When feasible, this is the best solution, but most databases are not written in such a way that this can be done. Some examples of pure Perl drivers are \fBDBD::File\fR and \fBDBD::CSV\fR. .PP Alternatively, and most commonly, your driver will need to use some C code to gain access to the database. This will be classified as a C/XS driver. .SS "What code will you write?" .IX Subsection "What code will you write?" There are a number of files that need to be written for either a pure Perl driver or a C/XS driver. There are no extra files needed only by a pure Perl driver, but there are several extra files needed only by a C/XS driver. .PP \fIFiles common to pure Perl and C/XS drivers\fR .IX Subsection "Files common to pure Perl and C/XS drivers" .PP Assuming that your driver is called \fBDBD::Driver\fR, these files are: .IP \(bu 4 \&\fIMakefile.PL\fR .IP \(bu 4 \&\fIMETA.yml\fR .IP \(bu 4 \&\fIREADME\fR .IP \(bu 4 \&\fIMANIFEST\fR .IP \(bu 4 \&\fIDriver.pm\fR .IP \(bu 4 \&\fIlib/Bundle/DBD/Driver.pm\fR .IP \(bu 4 \&\fIlib/DBD/Driver/Summary.pm\fR .IP \(bu 4 \&\fIt/*.t\fR .PP The first four files are mandatory. \fIMakefile.PL\fR is used to control how the driver is built and installed. The \fIREADME\fR file tells people who download the file about how to build the module and any prerequisite software that must be installed. The \fIMANIFEST\fR file is used by the standard Perl module distribution mechanism. It lists all the source files that need to be distributed with your module. \fIDriver.pm\fR is what is loaded by the \fBDBI\fR code; it contains the methods peculiar to your driver. .PP Although the \fIMETA.yml\fR file is not \fBrequired\fR you are advised to create one. Of particular importance are the \fIbuild_requires\fR and \&\fIconfigure_requires\fR attributes which newer CPAN modules understand. You use these to tell the CPAN module (and CPANPLUS) that your build and configure mechanisms require DBI. The best reference for META.yml (at the time of writing) is . You can find a reasonable example of a \fIMETA.yml\fR in DBD::ODBC. .PP The \fIlib/Bundle/DBD/Driver.pm\fR file allows you to specify other Perl modules on which yours depends in a format that allows someone to type a simple command and ensure that all the pre-requisites are in place as well as building your driver. .PP The \fIlib/DBD/Driver/Summary.pm\fR file contains (an updated version of) the information that was included \- or that would have been included \- in the appendices of the Cheetah book as a summary of the abilities of your driver and the associated database. .PP The files in the \fIt\fR subdirectory are unit tests for your driver. You should write your tests as stringently as possible, while taking into account the diversity of installations that you can encounter: .IP \(bu 4 Your tests should not casually modify operational databases. .IP \(bu 4 You should never damage existing tables in a database. .IP \(bu 4 You should code your tests to use a constrained name space within the database. For example, the tables (and all other named objects) that are created could all begin with '\fIdbd_drv_\fR'. .IP \(bu 4 At the end of a test run, there should be no testing objects left behind in the database. .IP \(bu 4 If you create any databases, you should remove them. .IP \(bu 4 If your database supports temporary tables that are automatically removed at the end of a session, then exploit them as often as possible. .IP \(bu 4 Try to make your tests independent of each other. If you have a test \fIt/t11dowhat.t\fR that depends upon the successful running of \fIt/t10thingamy.t\fR, people cannot run the single test case \&\fIt/t11dowhat.t\fR. Further, running \fIt/t11dowhat.t\fR twice in a row is likely to fail (at least, if \fIt/t11dowhat.t\fR modifies the database at all) because the database at the start of the second run is not what you saw at the start of the first run. .IP \(bu 4 Document in your \fIREADME\fR file what you do, and what privileges people need to do it. .IP \(bu 4 You can, and probably should, sequence your tests by including a test number before an abbreviated version of the test name; the tests are run in the order in which the names are expanded by shell-style globbing. .IP \(bu 4 It is in your interests to ensure that your tests work as widely as possible. .PP Many drivers also install sub-modules \fBDBD::Driver::SubModule\fR for any of a variety of different reasons, such as to support the metadata methods (see the discussion of "METADATA METHODS" below). Such sub-modules are conventionally stored in the directory \&\fIlib/DBD/Driver\fR. The module itself would usually be in a file \&\fISubModule.pm\fR. All such sub-modules should themselves be version stamped (see the discussions far below). .PP \fIExtra files needed by C/XS drivers\fR .IX Subsection "Extra files needed by C/XS drivers" .PP The software for a C/XS driver will typically contain at least four extra files that are not relevant to a pure Perl driver. .IP \(bu 4 \&\fIDriver.xs\fR .IP \(bu 4 \&\fIDriver.h\fR .IP \(bu 4 \&\fIdbdimp.h\fR .IP \(bu 4 \&\fIdbdimp.c\fR .PP The \fIDriver.xs\fR file is used to generate C code that Perl can call to gain access to the C functions you write that will, in turn, call down onto your database software. .PP The \fIDriver.h\fR header is a stylized header that ensures you can access the necessary Perl and \fBDBI\fR macros, types, and function declarations. .PP The \fIdbdimp.h\fR is used to specify which functions have been implemented by your driver. .PP The \fIdbdimp.c\fR file is where you write the C code that does the real work of translating between Perl-ish data types and what the database expects to use and return. .PP There are some (mainly small, but very important) differences between the contents of \fIMakefile.PL\fR and \fIDriver.pm\fR for pure Perl and C/XS drivers, so those files are described both in the section on creating a pure Perl driver and in the section on creating a C/XS driver. .PP Obviously, you can add extra source code files to the list. .SS "Requirements on a driver and driver writer" .IX Subsection "Requirements on a driver and driver writer" To be remotely useful, your driver must be implemented in a format that allows it to be distributed via CPAN, the Comprehensive Perl Archive Network ( and ). Of course, it is easier if you do not have to meet this criterion, but you will not be able to ask for much help if you do not do so, and no-one is likely to want to install your module if they have to learn a new installation mechanism. .SH "CREATING A PURE PERL DRIVER" .IX Header "CREATING A PURE PERL DRIVER" Writing a pure Perl driver is surprisingly simple. However, there are some problems you should be aware of. The best option is of course picking up an existing driver and carefully modifying one method after the other. .PP Also look carefully at \fBDBD::AnyData\fR and \fBDBD::Template\fR. .PP As an example we take a look at the \fBDBD::File\fR driver, a driver for accessing plain files as tables, which is part of the \fBDBD::CSV\fR package. .PP The minimal set of files we have to implement are \fIMakefile.PL\fR, \&\fIREADME\fR, \fIMANIFEST\fR and \fIDriver.pm\fR. .SS "Pure Perl version of Makefile.PL" .IX Subsection "Pure Perl version of Makefile.PL" You typically start with writing \fIMakefile.PL\fR, a Makefile generator. The contents of this file are described in detail in the ExtUtils::MakeMaker man pages. It is definitely a good idea if you start reading them. At least you should know about the variables \fICONFIGURE\fR, \fIDEFINED\fR, \fIPM\fR, \fIDIR\fR, \fIEXE_FILES\fR, \&\fIINC\fR, \fILIBS\fR, \fILINKTYPE\fR, \fINAME\fR, \fIOPTIMIZE\fR, \fIPL_FILES\fR, \&\fIVERSION\fR, \fIVERSION_FROM\fR, \fIclean\fR, \fIdepend\fR, \fIrealclean\fR from the ExtUtils::MakeMaker man page: these are used in almost any \&\fIMakefile.PL\fR. .PP Additionally read the section on \fIOverriding MakeMaker Methods\fR and the descriptions of the \fIdistcheck\fR, \fIdisttest\fR and \fIdist\fR targets: They will definitely be useful for you. .PP Of special importance for \fBDBI\fR drivers is the \fIpostamble\fR method from the ExtUtils::MM_Unix man page. .PP For Emacs users, I recommend the \fIlibscan\fR method, which removes Emacs backup files (file names which end with a tilde '~') from lists of files. .PP Now an example, I use the word \f(CW\*(C`Driver\*(C'\fR wherever you should insert your driver's name: .PP .Vb 1 \& # \-*\- perl \-*\- \& \& use ExtUtils::MakeMaker; \& \& WriteMakefile( \& dbd_edit_mm_attribs( { \& \*(AqNAME\*(Aq => \*(AqDBD::Driver\*(Aq, \& \*(AqVERSION_FROM\*(Aq => \*(AqDriver.pm\*(Aq, \& \*(AqINC\*(Aq => \*(Aq\*(Aq, \& \*(Aqdist\*(Aq => { \*(AqSUFFIX\*(Aq => \*(Aq.gz\*(Aq, \& \*(AqCOMPRESS\*(Aq => \*(Aqgzip \-9f\*(Aq }, \& \*(Aqrealclean\*(Aq => { FILES => \*(Aq*.xsi\*(Aq }, \& \*(AqPREREQ_PM\*(Aq => \*(Aq1.03\*(Aq, \& \*(AqCONFIGURE\*(Aq => sub { \& eval {require DBI::DBD;}; \& if ($@) { \& warn $@; \& exit 0; \& } \& my $dbi_arch_dir = dbd_dbi_arch_dir(); \& if (exists($opts{INC})) { \& return {INC => "$opts{INC} \-I$dbi_arch_dir"}; \& } else { \& return {INC => "\-I$dbi_arch_dir"}; \& } \& } \& }, \& { create_pp_tests => 1}) \& ); \& \& package MY; \& sub postamble { return main::dbd_postamble(@_); } \& sub libscan { \& my ($self, $path) = @_; \& ($path =~ m/\e~$/) ? undef : $path; \& } .Ve .PP Note the calls to \f(CWdbd_edit_mm_attribs()\fR and \f(CWdbd_postamble()\fR. .PP The second hash reference in the call to \f(CWdbd_edit_mm_attribs()\fR (containing \f(CWcreate_pp_tests()\fR) is optional; you should not use it unless your driver is a pure Perl driver (that is, it does not use C and XS code). Therefore, the call to \f(CWdbd_edit_mm_attribs()\fR is not relevant for C/XS drivers and may be omitted; simply use the (single) hash reference containing NAME etc as the only argument to \f(CWWriteMakefile()\fR. .PP Note that the \f(CWdbd_edit_mm_attribs()\fR code will fail if you do not have a \&\fIt\fR sub-directory containing at least one test case. .PP \&\fIPREREQ_PM\fR tells MakeMaker that DBI (version 1.03 in this case) is required for this module. This will issue a warning that DBI 1.03 is missing if someone attempts to install your DBD without DBI 1.03. See \&\fICONFIGURE\fR below for why this does not work reliably in stopping cpan testers failing your module if DBI is not installed. .PP \&\fICONFIGURE\fR is a subroutine called by MakeMaker during \&\f(CW\*(C`WriteMakefile\*(C'\fR. By putting the \f(CW\*(C`require DBI::DBD\*(C'\fR in this section we can attempt to load DBI::DBD but if it is missing we exit with success. As we exit successfully without creating a Makefile when DBI::DBD is missing cpan testers will not report a failure. This may seem at odds with \fIPREREQ_PM\fR but \fIPREREQ_PM\fR does not cause \&\f(CW\*(C`WriteMakefile\*(C'\fR to fail (unless you also specify PREREQ_FATAL which is strongly discouraged by MakeMaker) so \f(CW\*(C`WriteMakefile\*(C'\fR would continue to call \f(CW\*(C`dbd_dbi_arch_dir\*(C'\fR and fail. .PP All drivers must use \f(CWdbd_postamble()\fR or risk running into problems. .PP Note the specification of \fIVERSION_FROM\fR; the named file (\fIDriver.pm\fR) will be scanned for the first line that looks like an assignment to \fR\f(CI$VERSION\fR\fI\fR, and the subsequent text will be used to determine the version number. Note the commentary in ExtUtils::MakeMaker on the subject of correctly formatted version numbers. .PP If your driver depends upon external software (it usually will), you will need to add code to ensure that your environment is workable before the call to \f(CWWriteMakefile()\fR. If you need to check for the existence of an external library and perhaps modify \fIINC\fR to include the paths to where the external library header files are located and you cannot find the library or header files make sure you output a message saying they cannot be found but \f(CW\*(C`exit 0\*(C'\fR (success) \fBbefore\fR calling \f(CW\*(C`WriteMakefile\*(C'\fR or CPAN testers will fail your module if the external library is not found. .PP A full-fledged \fIMakefile.PL\fR can be quite large (for example, the files for \fBDBD::Oracle\fR and \fBDBD::Informix\fR are both over 1000 lines long, and the Informix one uses \- and creates \- auxiliary modules too). .PP See also ExtUtils::MakeMaker and ExtUtils::MM_Unix. Consider using CPAN::MakeMaker in place of \fIExtUtils::MakeMaker\fR. .SS README .IX Subsection "README" The README file should describe what the driver is for, the pre-requisites for the build process, the actual build process, how to report errors, and who to report them to. .PP Users will find ways of breaking the driver build and test process which you would never even have dreamed to be possible in your worst nightmares. Therefore, you need to write this document defensively, precisely and concisely. .PP As always, use the \fIREADME\fR from one of the established drivers as a basis for your own; the version in \fBDBD::Informix\fR is worth a look as it has been quite successful in heading off problems. .IP \(bu 4 Note that users will have versions of Perl and \fBDBI\fR that are both older and newer than you expected, but this will seldom cause much trouble. When it does, it will be because you are using features of \fBDBI\fR that are not supported in the version they are using. .IP \(bu 4 Note that users will have versions of the database software that are both older and newer than you expected. You will save yourself time in the long run if you can identify the range of versions which have been tested and warn about versions which are not known to be OK. .IP \(bu 4 Note that many people trying to install your driver will not be experts in the database software. .IP \(bu 4 Note that many people trying to install your driver will not be experts in C or Perl. .SS MANIFEST .IX Subsection "MANIFEST" The \fIMANIFEST\fR will be used by the Makefile's dist target to build the distribution tar file that is uploaded to CPAN. It should list every file that you want to include in your distribution, one per line. .SS lib/Bundle/DBD/Driver.pm .IX Subsection "lib/Bundle/DBD/Driver.pm" The CPAN module provides an extremely powerful bundle mechanism that allows you to specify pre-requisites for your driver. .PP The primary pre-requisite is \fBBundle::DBI\fR; you may want or need to add some more. With the bundle set up correctly, the user can type: .PP .Vb 1 \& perl \-MCPAN \-e \*(Aqinstall Bundle::DBD::Driver\*(Aq .Ve .PP and Perl will download, compile, test and install all the Perl modules needed to build your driver. .PP The prerequisite modules are listed in the \f(CW\*(C`CONTENTS\*(C'\fR section, with the official name of the module followed by a dash and an informal name or description. .IP \(bu 4 Listing \fBBundle::DBI\fR as the main pre-requisite simplifies life. .IP \(bu 4 Don't forget to list your driver. .IP \(bu 4 Note that unless the DBMS is itself a Perl module, you cannot list it as a pre-requisite in this file. .IP \(bu 4 You should keep the version of the bundle the same as the version of your driver. .IP \(bu 4 You should add configuration management, copyright, and licencing information at the top. .PP A suitable skeleton for this file is shown below. .PP .Vb 1 \& package Bundle::DBD::Driver; \& \& $VERSION = \*(Aq0.01\*(Aq; \& \& 1; \& \& _\|_END_\|_ \& \& =head1 NAME \& \& Bundle::DBD::Driver \- A bundle to install all DBD::Driver related modules \& \& =head1 SYNOPSIS \& \& C \& \& =head1 CONTENTS \& \& Bundle::DBI \- Bundle for DBI by TIMB (Tim Bunce) \& \& DBD::Driver \- DBD::Driver by YOU (Your Name) \& \& =head1 DESCRIPTION \& \& This bundle includes all the modules used by the Perl Database \& Interface (DBI) driver for Driver (DBD::Driver), assuming the \& use of DBI version 1.13 or later, created by Tim Bunce. \& \& If you\*(Aqve not previously used the CPAN module to install any \& bundles, you will be interrogated during its setup phase. \& But when you\*(Aqve done it once, it remembers what you told it. \& You could start by running: \& \& C \& \& =head1 SEE ALSO \& \& Bundle::DBI \& \& =head1 AUTHOR \& \& Your Name EFE \& \& =head1 THANKS \& \& This bundle was created by ripping off Bundle::libnet created by \& Graham Barr EFE, and radically simplified \& with some information from Jochen Wiedmann EFE. \& The template was then included in the DBI::DBD documentation by \& Jonathan Leffler EFE. \& \& =cut .Ve .SS lib/DBD/Driver/Summary.pm .IX Subsection "lib/DBD/Driver/Summary.pm" There is no substitute for taking the summary file from a driver that was documented in the Perl book (such as \fBDBD::Oracle\fR or \fBDBD::Informix\fR or \&\fBDBD::ODBC\fR, to name but three), and adapting it to describe the facilities available via \fBDBD::Driver\fR when accessing the Driver database. .SS "Pure Perl version of Driver.pm" .IX Subsection "Pure Perl version of Driver.pm" The \fIDriver.pm\fR file defines the Perl module \fBDBD::Driver\fR for your driver. It will define a package \fBDBD::Driver\fR along with some version information, some variable definitions, and a function \f(CWdriver()\fR which will have a more or less standard structure. .PP It will also define three sub-packages of \fBDBD::Driver\fR: .IP DBD::Driver::dr 4 .IX Item "DBD::Driver::dr" with methods \f(CWconnect()\fR, \f(CWdata_sources()\fR and \f(CWdisconnect_all()\fR; .IP DBD::Driver::db 4 .IX Item "DBD::Driver::db" with methods such as \f(CWprepare()\fR; .IP DBD::Driver::st 4 .IX Item "DBD::Driver::st" with methods such as \f(CWexecute()\fR and \f(CWfetch()\fR. .PP The \fIDriver.pm\fR file will also contain the documentation specific to \&\fBDBD::Driver\fR in the format used by perldoc. .PP In a pure Perl driver, the \fIDriver.pm\fR file is the core of the implementation. You will need to provide all the key methods needed by \fBDBI\fR. .PP Now let's take a closer look at an excerpt of \fIFile.pm\fR as an example. We ignore things that are common to any module (even non-DBI modules) or really specific to the \fBDBD::File\fR package. .PP \fIThe DBD::Driver package\fR .IX Subsection "The DBD::Driver package" .PP The header .IX Subsection "The header" .PP .Vb 1 \& package DBD::File; \& \& use strict; \& use vars qw($VERSION $drh); \& \& $VERSION = "1.23.00" # Version number of DBD::File .Ve .PP This is where the version number of your driver is specified, and is where \fIMakefile.PL\fR looks for this information. Please ensure that any other modules added with your driver are also version stamped so that CPAN does not get confused. .PP It is recommended that you use a two-part (1.23) or three-part (1.23.45) version number. Also consider the CPAN system, which gets confused and considers version 1.10 to precede version 1.9, so that using a raw CVS, RCS or SCCS version number is probably not appropriate (despite being very common). .PP For Subversion you could use: .PP .Vb 1 \& $VERSION = "12.012346"; .Ve .PP (use lots of leading zeros on the second portion so if you move the code to a shared repository like svn.perl.org the much larger revision numbers won't cause a problem, at least not for a few years). For RCS or CVS you can use: .PP .Vb 1 \& $VERSION = "11.22"; .Ve .PP which pads out the fractional part with leading zeros so all is well (so long as you don't go past x.99) .PP .Vb 1 \& $drh = undef; # holds driver handle once initialized .Ve .PP This is where the driver handle will be stored, once created. Note that you may assume there is only one handle for your driver. .PP The driver constructor .IX Subsection "The driver constructor" .PP The \f(CWdriver()\fR method is the driver handle constructor. Note that the \f(CWdriver()\fR method is in the \fBDBD::Driver\fR package, not in one of the sub-packages \fBDBD::Driver::dr\fR, \fBDBD::Driver::db\fR, or \&\fBDBD::Driver::db\fR. .PP .Vb 4 \& sub driver \& { \& return $drh if $drh; # already created \- return same one \& my ($class, $attr) = @_; \& \& $class .= "::dr"; \& \& DBD::Driver::db\->install_method(\*(Aqdrv_example_dbh_method\*(Aq); \& DBD::Driver::st\->install_method(\*(Aqdrv_example_sth_method\*(Aq); \& \& # not a \*(Aqmy\*(Aq since we use it above to prevent multiple drivers \& $drh = DBI::_new_drh($class, { \& \*(AqName\*(Aq => \*(AqFile\*(Aq, \& \*(AqVersion\*(Aq => $VERSION, \& \*(AqAttribution\*(Aq => \*(AqDBD::File by Jochen Wiedmann\*(Aq, \& }) \& or return undef; \& \& return $drh; \& } .Ve .PP This is a reasonable example of how \fBDBI\fR implements its handles. There are three kinds: \fBdriver handles\fR (typically stored in \fR\f(CI$drh\fR\fI\fR; from now on called \fIdrh\fR or \fI\fR\f(CI$drh\fR\fI\fR), \fBdatabase handles\fR (from now on called \fIdbh\fR or \fI\fR\f(CI$dbh\fR\fI\fR) and \fBstatement handles\fR (from now on called \&\fIsth\fR or \fI\fR\f(CI$sth\fR\fI\fR). .PP The prototype of \f(CWDBI::_new_drh()\fR is .PP .Vb 1 \& $drh = DBI::_new_drh($class, $public_attrs, $private_attrs); .Ve .PP with the following arguments: .ie n .IP \fR\fI$class\fR\fI\fR 4 .el .IP \fR\f(CI$class\fR\fI\fR 4 .IX Item "$class" is typically the class for your driver, (for example, "DBD::File::dr"), passed as the first argument to the \f(CWdriver()\fR method. .ie n .IP \fR\fI$public_attrs\fR\fI\fR 4 .el .IP \fR\f(CI$public_attrs\fR\fI\fR 4 .IX Item "$public_attrs" is a hash ref to attributes like \fIName\fR, \fIVersion\fR, and \fIAttribution\fR. These are processed and used by \fBDBI\fR. You had better not make any assumptions about them nor should you add private attributes here. .ie n .IP \fR\fI$private_attrs\fR\fI\fR 4 .el .IP \fR\f(CI$private_attrs\fR\fI\fR 4 .IX Item "$private_attrs" This is another (optional) hash ref with your private attributes. \&\fBDBI\fR will store them and otherwise leave them alone. .PP The \f(CWDBI::_new_drh()\fR method and the \f(CWdriver()\fR method both return \f(CW\*(C`undef\*(C'\fR for failure (in which case you must look at \fR\f(CI$DBI::err\fR\fI\fR and \fI\fR\f(CI$DBI::errstr\fR\fI\fR for the failure information, because you have no driver handle to use). .PP Using \fBinstall_method()\fR to expose driver-private methods .IX Subsection "Using install_method() to expose driver-private methods" .PP .Vb 1 \& DBD::Foo::db\->install_method($method_name, \e%attr); .Ve .PP Installs the driver-private method named by \f(CW$method_name\fR into the DBI method dispatcher so it can be called directly, avoiding the need to use the \fBfunc()\fR method. .PP It is called as a static method on the driver class to which the method belongs. The method name must begin with the corresponding registered driver-private prefix. For example, for DBD::Oracle \&\f(CW$method_name\fR must being with '\f(CW\*(C`ora_\*(C'\fR', and for DBD::AnyData it must begin with '\f(CW\*(C`ad_\*(C'\fR'. .PP The \f(CW\*(C`\e%attr\*(C'\fR attributes can be used to provide fine control over how the DBI dispatcher handles the dispatching of the method. However it's undocumented at the moment. See the IMA_* #define's in DBI.xs and the O=>0x000x values in the initialization of \f(CW%DBI::DBI_methods\fR in DBI.pm. (Volunteers to polish up and document the interface are very welcome to get in touch via dbi\-dev@perl.org). .PP Methods installed using install_method default to the standard error handling behaviour for DBI methods: clearing err and errstr before calling the method, and checking for errors to trigger RaiseError etc. on return. This differs from the default behaviour of \fBfunc()\fR. .PP Note for driver authors: The DBD::Foo::xx\->install_method call won't work until the class-hierarchy has been setup. Normally the DBI looks after that just after the driver is loaded. This means \&\fBinstall_method()\fR can't be called at the time the driver is loaded unless the class-hierarchy is set up first. The way to do that is to call the \fBsetup_driver()\fR method: .PP .Vb 1 \& DBI\->setup_driver(\*(AqDBD::Foo\*(Aq); .Ve .PP before using \fBinstall_method()\fR. .PP The CLONE special subroutine .IX Subsection "The CLONE special subroutine" .PP Also needed here, in the \fBDBD::Driver\fR package, is a \f(CWCLONE()\fR method that will be called by perl when an interpreter is cloned. All your \&\f(CWCLONE()\fR method needs to do, currently, is clear the cached \fR\f(CI$drh\fR\fI\fR so the new interpreter won't start using the cached \fI\fR\f(CI$drh\fR\fI\fR from the old interpreter: .PP .Vb 3 \& sub CLONE { \& undef $drh; \& } .Ve .PP See for details. .PP \fIThe DBD::Driver::dr package\fR .IX Subsection "The DBD::Driver::dr package" .PP The next lines of code look as follows: .PP .Vb 1 \& package DBD::Driver::dr; # ====== DRIVER ====== \& \& $DBD::Driver::dr::imp_data_size = 0; .Ve .PP Note that no \fR\f(CI@ISA\fR\fI\fR is needed here, or for the other \fBDBD::Driver::*\fR classes, because the \fBDBI\fR takes care of that for you when the driver is loaded. .PP .Vb 2 \& *FIX ME* Explain what the imp_data_size is, so that implementors aren\*(Aqt \& practicing cargo\-cult programming. .Ve .PP The database handle constructor .IX Subsection "The database handle constructor" .PP The database handle constructor is the driver's (hence the changed namespace) \f(CWconnect()\fR method: .PP .Vb 3 \& sub connect \& { \& my ($drh, $dr_dsn, $user, $auth, $attr) = @_; \& \& # Some database specific verifications, default settings \& # and the like can go here. This should only include \& # syntax checks or similar stuff where it\*(Aqs legal to \& # \*(Aqdie\*(Aq in case of errors. \& # For example, many database packages requires specific \& # environment variables to be set; this could be where you \& # validate that they are set, or default them if they are not set. \& \& my $driver_prefix = "drv_"; # the assigned prefix for this driver \& \& # Process attributes from the DSN; we assume ODBC syntax \& # here, that is, the DSN looks like var1=val1;...;varN=valN \& foreach my $var ( split /;/, $dr_dsn ) { \& my ($attr_name, $attr_value) = split \*(Aq=\*(Aq, $var, 2; \& return $drh\->set_err($DBI::stderr, "Can\*(Aqt parse DSN part \*(Aq$var\*(Aq") \& unless defined $attr_value; \& \& # add driver prefix to attribute name if it doesn\*(Aqt have it already \& $attr_name = $driver_prefix.$attr_name \& unless $attr_name =~ /^$driver_prefix/o; \& \& # Store attribute into %$attr, replacing any existing value. \& # The DBI will STORE() these into $dbh after we\*(Aqve connected \& $attr\->{$attr_name} = $attr_value; \& } \& \& # Get the attributes we\*(Aqll use to connect. \& # We use delete here because these no need to STORE them \& my $db = delete $attr\->{drv_database} || delete $attr\->{drv_db} \& or return $drh\->set_err($DBI::stderr, "No database name given in DSN \*(Aq$dr_dsn\*(Aq"); \& my $host = delete $attr\->{drv_host} || \*(Aqlocalhost\*(Aq; \& my $port = delete $attr\->{drv_port} || 123456; \& \& # Assume you can attach to your database via drv_connect: \& my $connection = drv_connect($db, $host, $port, $user, $auth) \& or return $drh\->set_err($DBI::stderr, "Can\*(Aqt connect to $dr_dsn: ..."); \& \& # create a \*(Aqblank\*(Aq dbh (call superclass constructor) \& my ($outer, $dbh) = DBI::_new_dbh($drh, { Name => $dr_dsn }); \& \& $dbh\->STORE(\*(AqActive\*(Aq, 1 ); \& $dbh\->{drv_connection} = $connection; \& \& return $outer; \& } .Ve .PP This is mostly the same as in the \fIdriver handle constructor\fR above. The arguments are described in DBI. .PP The constructor \f(CWDBI::_new_dbh()\fR is called, returning a database handle. The constructor's prototype is: .PP .Vb 1 \& ($outer, $inner) = DBI::_new_dbh($drh, $public_attr, $private_attr); .Ve .PP with similar arguments to those in the \fIdriver handle constructor\fR, except that the \fR\f(CI$class\fR\fI\fR is replaced by \fI\fR\f(CI$drh\fR\fI\fR. The \fIName\fR attribute is a standard \fBDBI\fR attribute (see "Database Handle Attributes" in DBI). .PP In scalar context, only the outer handle is returned. .PP Note the use of the \f(CWSTORE()\fR method for setting the \fIdbh\fR attributes. That's because within the driver code, the handle object you have is the 'inner' handle of a tied hash, not the outer handle that the users of your driver have. .PP Because you have the inner handle, tie magic doesn't get invoked when you get or set values in the hash. This is often very handy for speed when you want to get or set simple non-special driver-specific attributes. .PP However, some attribute values, such as those handled by the \fBDBI\fR like \&\fIPrintError\fR, don't actually exist in the hash and must be read via \&\f(CW\*(C`$h\->FETCH($attrib)\*(C'\fR and set via \f(CW\*(C`$h\->STORE($attrib, $value)\*(C'\fR. If in any doubt, use these methods. .PP The \fBdata_sources()\fR method .IX Subsection "The data_sources() method" .PP The \f(CWdata_sources()\fR method must populate and return a list of valid data sources, prefixed with the "\fIdbi:Driver\fR" incantation that allows them to be used in the first argument of the \f(CW\*(C`DBI\->connect()\*(C'\fR method. An example of this might be scanning the \fR\f(CI$HOME\fR\fI/.odbcini\fR file on Unix for ODBC data sources (DSNs). .PP As a trivial example, consider a fixed list of data sources: .PP .Vb 11 \& sub data_sources \& { \& my($drh, $attr) = @_; \& my(@list) = (); \& # You need more sophisticated code than this to set @list... \& push @list, "dbi:Driver:abc"; \& push @list, "dbi:Driver:def"; \& push @list, "dbi:Driver:ghi"; \& # End of code to set @list \& return @list; \& } .Ve .PP The \fBdisconnect_all()\fR method .IX Subsection "The disconnect_all() method" .PP If you need to release any resources when the driver is unloaded, you can provide a disconnect_all method. .PP Other driver handle methods .IX Subsection "Other driver handle methods" .PP If you need any other driver handle methods, they can follow here. .PP Error handling .IX Subsection "Error handling" .PP It is quite likely that something fails in the connect method. With \fBDBD::File\fR for example, you might catch an error when setting the current directory to something not existent by using the (driver-specific) \fIf_dir\fR attribute. .PP To report an error, you use the \f(CWset_err()\fR method: .PP .Vb 1 \& $h\->set_err($err, $errmsg, $state); .Ve .PP This will ensure that the error is recorded correctly and that \&\fIRaiseError\fR and \fIPrintError\fR etc are handled correctly. .PP Typically you'll always use the method instance, aka your method's first argument. .PP As \f(CWset_err()\fR always returns \f(CW\*(C`undef\*(C'\fR your error handling code can usually be simplified to something like this: .PP .Vb 1 \& return $h\->set_err($err, $errmsg, $state) if ...; .Ve .PP \fIThe DBD::Driver::db package\fR .IX Subsection "The DBD::Driver::db package" .PP .Vb 1 \& package DBD::Driver::db; # ====== DATABASE ====== \& \& $DBD::Driver::db::imp_data_size = 0; .Ve .PP The statement handle constructor .IX Subsection "The statement handle constructor" .PP There's nothing much new in the statement handle constructor, which is the \f(CWprepare()\fR method: .PP .Vb 3 \& sub prepare \& { \& my ($dbh, $statement, @attribs) = @_; \& \& # create a \*(Aqblank\*(Aq sth \& my ($outer, $sth) = DBI::_new_sth($dbh, { Statement => $statement }); \& \& $sth\->STORE(\*(AqNUM_OF_PARAMS\*(Aq, ($statement =~ tr/?//)); \& \& $sth\->{drv_params} = []; \& \& return $outer; \& } .Ve .PP This is still the same \-\- check the arguments and call the super class constructor \f(CWDBI::_new_sth()\fR. Again, in scalar context, only the outer handle is returned. The \fIStatement\fR attribute should be cached as shown. .PP Note the prefix \fIdrv_\fR in the attribute names: it is required that all your private attributes use a lowercase prefix unique to your driver. As mentioned earlier in this document, the \fBDBI\fR contains a registry of known driver prefixes and may one day warn about unknown attributes that don't have a registered prefix. .PP Note that we parse the statement here in order to set the attribute \&\fINUM_OF_PARAMS\fR. The technique illustrated is not very reliable; it can be confused by question marks appearing in quoted strings, delimited identifiers or in SQL comments that are part of the SQL statement. We could set \fINUM_OF_PARAMS\fR in the \f(CWexecute()\fR method instead because the \fBDBI\fR specification explicitly allows a driver to defer this, but then the user could not call \f(CWbind_param()\fR. .PP Transaction handling .IX Subsection "Transaction handling" .PP Pure Perl drivers will rarely support transactions. Thus your \f(CWcommit()\fR and \f(CWrollback()\fR methods will typically be quite simple: .PP .Vb 8 \& sub commit \& { \& my ($dbh) = @_; \& if ($dbh\->FETCH(\*(AqWarn\*(Aq)) { \& warn("Commit ineffective while AutoCommit is on"); \& } \& 0; \& } \& \& sub rollback { \& my ($dbh) = @_; \& if ($dbh\->FETCH(\*(AqWarn\*(Aq)) { \& warn("Rollback ineffective while AutoCommit is on"); \& } \& 0; \& } .Ve .PP Or even simpler, just use the default methods provided by the \fBDBI\fR that do nothing except return \f(CW\*(C`undef\*(C'\fR. .PP The \fBDBI\fR's default \f(CWbegin_work()\fR method can be used by inheritance. .PP The \fBSTORE()\fR and \fBFETCH()\fR methods .IX Subsection "The STORE() and FETCH() methods" .PP These methods (that we have already used, see above) are called for you, whenever the user does a: .PP .Vb 1 \& $dbh\->{$attr} = $val; .Ve .PP or, respectively, .PP .Vb 1 \& $val = $dbh\->{$attr}; .Ve .PP See perltie for details on tied hash refs to understand why these methods are required. .PP The \fBDBI\fR will handle most attributes for you, in particular attributes like \fIRaiseError\fR or \fIPrintError\fR. All you have to do is handle your driver's private attributes and any attributes, like \fIAutoCommit\fR and \&\fIChopBlanks\fR, that the \fBDBI\fR can't handle for you. .PP A good example might look like this: .PP .Vb 10 \& sub STORE \& { \& my ($dbh, $attr, $val) = @_; \& if ($attr eq \*(AqAutoCommit\*(Aq) { \& # AutoCommit is currently the only standard attribute we have \& # to consider. \& if (!$val) { die "Can\*(Aqt disable AutoCommit"; } \& return 1; \& } \& if ($attr =~ m/^drv_/) { \& # Handle only our private attributes here \& # Note that we could trigger arbitrary actions. \& # Ideally we should warn about unknown attributes. \& $dbh\->{$attr} = $val; # Yes, we are allowed to do this, \& return 1; # but only for our private attributes \& } \& # Else pass up to DBI to handle for us \& $dbh\->SUPER::STORE($attr, $val); \& } \& \& sub FETCH \& { \& my ($dbh, $attr) = @_; \& if ($attr eq \*(AqAutoCommit\*(Aq) { return 1; } \& if ($attr =~ m/^drv_/) { \& # Handle only our private attributes here \& # Note that we could trigger arbitrary actions. \& return $dbh\->{$attr}; # Yes, we are allowed to do this, \& # but only for our private attributes \& } \& # Else pass up to DBI to handle \& $dbh\->SUPER::FETCH($attr); \& } .Ve .PP The \fBDBI\fR will actually store and fetch driver-specific attributes (with all lowercase names) without warning or error, so there's actually no need to implement driver-specific any code in your \f(CWFETCH()\fR and \f(CWSTORE()\fR methods unless you need extra logic/checks, beyond getting or setting the value. .PP Unless your driver documentation indicates otherwise, the return value of the \f(CWSTORE()\fR method is unspecified and the caller shouldn't use that value. .PP Other database handle methods .IX Subsection "Other database handle methods" .PP As with the driver package, other database handle methods may follow here. In particular you should consider a (possibly empty) \f(CWdisconnect()\fR method and possibly a \f(CWquote()\fR method if \fBDBI\fR's default isn't correct for you. You may also need the \f(CWtype_info_all()\fR and \f(CWget_info()\fR methods, as described elsewhere in this document. .PP Where reasonable use \f(CW\*(C`$h\->SUPER::foo()\*(C'\fR to call the \fBDBI\fR's method in some or all cases and just wrap your custom behavior around that. .PP If you want to use private trace flags you'll probably want to be able to set them by name. To do that you'll need to define a \&\f(CWparse_trace_flag()\fR method (note that's "parse_trace_flag", singular, not "parse_trace_flags", plural). .PP .Vb 9 \& sub parse_trace_flag { \& my ($h, $name) = @_; \& return 0x01000000 if $name eq \*(Aqfoo\*(Aq; \& return 0x02000000 if $name eq \*(Aqbar\*(Aq; \& return 0x04000000 if $name eq \*(Aqbaz\*(Aq; \& return 0x08000000 if $name eq \*(Aqboo\*(Aq; \& return 0x10000000 if $name eq \*(Aqbop\*(Aq; \& return $h\->SUPER::parse_trace_flag($name); \& } .Ve .PP All private flag names must be lowercase, and all private flags must be in the top 8 of the 32 bits. .PP \fIThe DBD::Driver::st package\fR .IX Subsection "The DBD::Driver::st package" .PP This package follows the same pattern the others do: .PP .Vb 1 \& package DBD::Driver::st; \& \& $DBD::Driver::st::imp_data_size = 0; .Ve .PP The \fBexecute()\fR and \fBbind_param()\fR methods .IX Subsection "The execute() and bind_param() methods" .PP This is perhaps the most difficult method because we have to consider parameter bindings here. In addition to that, there are a number of statement attributes which must be set for inherited \fBDBI\fR methods to function correctly (see "Statement attributes" below). .PP We present a simplified implementation by using the \fIdrv_params\fR attribute from above: .PP .Vb 12 \& sub bind_param \& { \& my ($sth, $pNum, $val, $attr) = @_; \& my $type = (ref $attr) ? $attr\->{TYPE} : $attr; \& if ($type) { \& my $dbh = $sth\->{Database}; \& $val = $dbh\->quote($sth, $type); \& } \& my $params = $sth\->{drv_params}; \& $params\->[$pNum\-1] = $val; \& 1; \& } \& \& sub execute \& { \& my ($sth, @bind_values) = @_; \& \& # start of by finishing any previous execution if still active \& $sth\->finish if $sth\->FETCH(\*(AqActive\*(Aq); \& \& my $params = (@bind_values) ? \& \e@bind_values : $sth\->{drv_params}; \& my $numParam = $sth\->FETCH(\*(AqNUM_OF_PARAMS\*(Aq); \& return $sth\->set_err($DBI::stderr, "Wrong number of parameters") \& if @$params != $numParam; \& my $statement = $sth\->{\*(AqStatement\*(Aq}; \& for (my $i = 0; $i < $numParam; $i++) { \& $statement =~ s/?/$params\->[$i]/; # XXX doesn\*(Aqt deal with quoting etc! \& } \& # Do anything ... we assume that an array ref of rows is \& # created and store it: \& $sth\->{\*(Aqdrv_data\*(Aq} = $data; \& $sth\->{\*(Aqdrv_rows\*(Aq} = @$data; # number of rows \& $sth\->STORE(\*(AqNUM_OF_FIELDS\*(Aq) = $numFields; \& $sth\->{Active} = 1; \& @$data || \*(Aq0E0\*(Aq; \& } .Ve .PP There are a number of things you should note here. .PP We initialize the \fINUM_OF_FIELDS\fR and \fIActive\fR attributes here, because they are essential for \f(CWbind_columns()\fR to work. .PP We use attribute \f(CW\*(C`$sth\->{Statement}\*(C'\fR which we created within \f(CWprepare()\fR. The attribute \f(CW\*(C`$sth\->{Database}\*(C'\fR, which is nothing else than the \fIdbh\fR, was automatically created by \fBDBI\fR. .PP Finally, note that (as specified in the \fBDBI\fR specification) we return the string \f(CW\*(Aq0E0\*(Aq\fR instead of the number 0, so that the result tests true but equal to zero. .PP .Vb 1 \& $sth\->execute() or die $sth\->errstr; .Ve .PP The \fBexecute_array()\fR, \fBexecute_for_fetch()\fR and \fBbind_param_array()\fR methods .IX Subsection "The execute_array(), execute_for_fetch() and bind_param_array() methods" .PP In general, DBD's only need to implement \f(CWexecute_for_fetch()\fR and \&\f(CW\*(C`bind_param_array\*(C'\fR. DBI's default \f(CWexecute_array()\fR will invoke the DBD's \f(CWexecute_for_fetch()\fR as needed. .PP The following sequence describes the interaction between DBI \f(CW\*(C`execute_array\*(C'\fR and a DBD's \f(CW\*(C`execute_for_fetch\*(C'\fR: .IP 1. 4 App calls \f(CW\*(C`$sth\->execute_array(\e%attrs, @array_of_arrays)\*(C'\fR .IP 2. 4 If \f(CW@array_of_arrays\fR was specified, DBI processes \f(CW@array_of_arrays\fR by calling DBD's \f(CWbind_param_array()\fR. Alternately, App may have directly called \&\f(CWbind_param_array()\fR .IP 3. 4 DBD validates and binds each array .IP 4. 4 DBI retrieves the validated param arrays from DBD's ParamArray attribute .IP 5. 4 DBI calls DBD's \f(CW\*(C`execute_for_fetch($fetch_tuple_sub, \e@tuple_status)\*(C'\fR, where \f(CW&$fetch_tuple_sub\fR is a closure to iterate over the returned ParamArray values, and \f(CW\*(C`\e@tuple_status\*(C'\fR is an array to receive the disposition status of each tuple. .IP 6. 4 DBD iteratively calls \f(CW&$fetch_tuple_sub\fR to retrieve parameter tuples to be added to its bulk database operation/request. .IP 7. 4 when DBD reaches the limit of tuples it can handle in a single database operation/request, or the \f(CW&$fetch_tuple_sub\fR indicates no more tuples by returning undef, the DBD executes the bulk operation, and reports the disposition of each tuple in \e@tuple_status. .IP 8. 4 DBD repeats steps 6 and 7 until all tuples are processed. .PP E.g., here's the essence of DBD::Oracle's execute_for_fetch: .PP .Vb 10 \& while (1) { \& my @tuple_batch; \& for (my $i = 0; $i < $batch_size; $i++) { \& push @tuple_batch, [ @{$fetch_tuple_sub\->() || last} ]; \& } \& last unless @tuple_batch; \& my $res = ora_execute_array($sth, \e@tuple_batch, \& scalar(@tuple_batch), $tuple_batch_status); \& push @$tuple_status, @$tuple_batch_status; \& } .Ve .PP Note that DBI's default \fBexecute_array()\fR/\fBexecute_for_fetch()\fR implementation requires the use of positional (i.e., '?') placeholders. Drivers which \fBrequire\fR named placeholders must either emulate positional placeholders (e.g., see DBD::Oracle), or must implement their own \&\fBexecute_array()\fR/\fBexecute_for_fetch()\fR methods to properly sequence bound parameter arrays. .PP Fetching data .IX Subsection "Fetching data" .PP Only one method needs to be written for fetching data, \f(CWfetchrow_arrayref()\fR. The other methods, \f(CWfetchrow_array()\fR, \f(CWfetchall_arrayref()\fR, etc, as well as the database handle's \f(CW\*(C`select*\*(C'\fR methods are part of \fBDBI\fR, and call \&\f(CWfetchrow_arrayref()\fR as necessary. .PP .Vb 10 \& sub fetchrow_arrayref \& { \& my ($sth) = @_; \& my $data = $sth\->{drv_data}; \& my $row = shift @$data; \& if (!$row) { \& $sth\->STORE(Active => 0); # mark as no longer active \& return undef; \& } \& if ($sth\->FETCH(\*(AqChopBlanks\*(Aq)) { \& map { $_ =~ s/\es+$//; } @$row; \& } \& return $sth\->_set_fbav($row); \& } \& *fetch = \e&fetchrow_arrayref; # required alias for fetchrow_arrayref .Ve .PP Note the use of the method \f(CW_set_fbav()\fR \-\- this is required so that \&\f(CWbind_col()\fR and \f(CWbind_columns()\fR work. .PP If an error occurs which leaves the \fR\f(CI$sth\fR\fI\fR in a state where remaining rows can't be fetched then \fIActive\fR should be turned off before the method returns. .PP The \f(CWrows()\fR method for this driver can be implemented like this: .PP .Vb 1 \& sub rows { shift\->{drv_rows} } .Ve .PP because it knows in advance how many rows it has fetched. Alternatively you could delete that method and so fallback to the \fBDBI\fR's own method which does the right thing based on the number of calls to \f(CW_set_fbav()\fR. .PP The more_results method .IX Subsection "The more_results method" .PP If your driver doesn't support multiple result sets, then don't even implement this method. .PP Otherwise, this method needs to get the statement handle ready to fetch results from the next result set, if there is one. Typically you'd start with: .PP .Vb 1 \& $sth\->finish; .Ve .PP then you should delete all the attributes from the attribute cache that may no longer be relevant for the new result set: .PP .Vb 2 \& delete $sth\->{$_} \& for qw(NAME TYPE PRECISION SCALE ...); .Ve .PP for drivers written in C use: .PP .Vb 6 \& hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD); \& hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD); \& hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD); \& hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD); \& hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD); \& hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD); .Ve .PP Don't forget to also delete, or update, any driver-private attributes that may not be correct for the next resultset. .PP The NUM_OF_FIELDS attribute is a special case. It should be set using STORE: .PP .Vb 2 \& $sth\->STORE(NUM_OF_FIELDS => 0); /* for DBI <= 1.53 */ \& $sth\->STORE(NUM_OF_FIELDS => $new_value); .Ve .PP for drivers written in C use this incantation: .PP .Vb 5 \& /* Adjust NUM_OF_FIELDS \- which also adjusts the row buffer size */ \& DBIc_NUM_FIELDS(imp_sth) = 0; /* for DBI <= 1.53 */ \& DBIc_STATE(imp_xxh)\->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0, \& sv_2mortal(newSViv(mysql_num_fields(imp_sth\->result))) \& ); .Ve .PP For DBI versions prior to 1.54 you'll also need to explicitly adjust the number of elements in the row buffer array (\f(CWDBIc_FIELDS_AV(imp_sth)\fR) to match the new result set. Fill any new values with \fBnewSV\fR\|(0) not &sv_undef. Alternatively you could free DBIc_FIELDS_AV(imp_sth) and set it to null, but that would mean \fBbind_columns()\fR wouldn't work across result sets. .PP Statement attributes .IX Subsection "Statement attributes" .PP The main difference between \fIdbh\fR and \fIsth\fR attributes is, that you should implement a lot of attributes here that are required by the \fBDBI\fR, such as \fINAME\fR, \fINULLABLE\fR, \fITYPE\fR, etc. See "Statement Handle Attributes" in DBI for a complete list. .PP Pay attention to attributes which are marked as read only, such as \&\fINUM_OF_PARAMS\fR. These attributes can only be set the first time a statement is executed. If a statement is prepared, then executed multiple times, warnings may be generated. .PP You can protect against these warnings, and prevent the recalculation of attributes which might be expensive to calculate (such as the \&\fINAME\fR and \fINAME_*\fR attributes): .PP .Vb 3 \& my $storedNumParams = $sth\->FETCH(\*(AqNUM_OF_PARAMS\*(Aq); \& if (!defined $storedNumParams or $storedNumFields < 0) { \& $sth\->STORE(\*(AqNUM_OF_PARAMS\*(Aq) = $numParams; \& \& # Set other useful attributes that only need to be set once \& # for a statement, like $sth\->{NAME} and $sth\->{TYPE} \& } .Ve .PP One particularly important attribute to set correctly (mentioned in "ATTRIBUTES COMMON TO ALL HANDLES" in DBI is \fIActive\fR. Many \fBDBI\fR methods, including \f(CWbind_columns()\fR, depend on this attribute. .PP Besides that the \f(CWSTORE()\fR and \f(CWFETCH()\fR methods are mainly the same as above for \fIdbh\fR's. .PP Other statement methods .IX Subsection "Other statement methods" .PP A trivial \f(CWfinish()\fR method to discard stored data, reset any attributes (such as \fIActive\fR) and do \f(CW\*(C`$sth\->SUPER::finish()\*(C'\fR. .PP If you've defined a \f(CWparse_trace_flag()\fR method in \fB::db\fR you'll also want it in \fB::st\fR, so just alias it in: .PP .Vb 1 \& *parse_trace_flag = \e&DBD::foo:db::parse_trace_flag; .Ve .PP And perhaps some other methods that are not part of the \fBDBI\fR specification, in particular to make metadata available. Remember that they must have names that begin with your drivers registered prefix so they can be installed using \f(CWinstall_method()\fR. .PP If \f(CWDESTROY()\fR is called on a statement handle that's still active (\f(CW\*(C`$sth\->{Active}\*(C'\fR is true) then it should effectively call \f(CWfinish()\fR. .PP .Vb 4 \& sub DESTROY { \& my $sth = shift; \& $sth\->finish if $sth\->FETCH(\*(AqActive\*(Aq); \& } .Ve .SS Tests .IX Subsection "Tests" The test process should conform as closely as possibly to the Perl standard test harness. .PP In particular, most (all) of the tests should be run in the \fIt\fR sub-directory, and should simply produce an \f(CW\*(C`ok\*(C'\fR when run under \f(CW\*(C`make test\*(C'\fR. For details on how this is done, see the Camel book and the section in Chapter 7, "The Standard Perl Library" on Test::Harness. .PP The tests may need to adapt to the type of database which is being used for testing, and to the privileges of the user testing the driver. For example, the \fBDBD::Informix\fR test code has to adapt in a number of places to the type of database to which it is connected as different Informix databases have different capabilities: some of the tests are for databases without transaction logs; others are for databases with a transaction log; some versions of the server have support for blobs, or stored procedures, or user-defined data types, and others do not. .PP When a complete file of tests must be skipped, you can provide a reason in a pseudo-comment: .PP .Vb 5 \& if ($no_transactions_available) \& { \& print "1..0 # Skip: No transactions available\en"; \& exit 0; \& } .Ve .PP Consider downloading the \fBDBD::Informix\fR code and look at the code in \&\fIDBD/Informix/TestHarness.pm\fR which is used throughout the \&\fBDBD::Informix\fR tests in the \fIt\fR sub-directory. .SH "CREATING A C/XS DRIVER" .IX Header "CREATING A C/XS DRIVER" Please also see the section under "CREATING A PURE PERL DRIVER" regarding the creation of the \fIMakefile.PL\fR. .PP Creating a new C/XS driver from scratch will always be a daunting task. You can and should greatly simplify your task by taking a good reference driver implementation and modifying that to match the database product for which you are writing a driver. .PP The de facto reference driver has been the one for \fBDBD::Oracle\fR written by Tim Bunce, who is also the author of the \fBDBI\fR package. The \fBDBD::Oracle\fR module is a good example of a driver implemented around a C\-level API. .PP Nowadays it it seems better to base on \fBDBD::ODBC\fR, another driver maintained by Tim and Jeff Urlwin, because it offers a lot of metadata and seems to become the guideline for the future development. (Also as \&\fBDBD::Oracle\fR digs deeper into the Oracle 8 OCI interface it'll get even more hairy than it is now.) .PP The \fBDBD::Informix\fR driver is one driver implemented using embedded SQL instead of a function-based API. \&\fBDBD::Ingres\fR may also be worth a look. .SS "C/XS version of Driver.pm" .IX Subsection "C/XS version of Driver.pm" A lot of the code in the \fIDriver.pm\fR file is very similar to the code for pure Perl modules \&\- see above. However, there are also some subtle (and not so subtle) differences, including: .IP \(bu 8 The variables \fR\f(CI$DBD::Driver::\fR\fI{dr|db|st}::imp_data_size\fR are not defined here, but in the XS code, because they declare the size of certain C structures. .IP \(bu 8 Some methods are typically moved to the XS code, in particular \&\f(CWprepare()\fR, \f(CWexecute()\fR, \f(CWdisconnect()\fR, \f(CWdisconnect_all()\fR and the \&\f(CWSTORE()\fR and \f(CWFETCH()\fR methods. .IP \(bu 8 Other methods are still part of \fIDriver.pm\fR, but have callbacks to the XS code. .IP \(bu 8 If the driver-specific parts of the \fIimp_drh_t\fR structure need to be formally initialized (which does not seem to be a common requirement), then you need to add a call to an appropriate XS function in the driver method of \f(CWDBD::Driver::driver()\fR, and you define the corresponding function in \fIDriver.xs\fR, and you define the C code in \fIdbdimp.c\fR and the prototype in \&\fIdbdimp.h\fR. .Sp For example, \fBDBD::Informix\fR has such a requirement, and adds the following call after the call to \f(CW_new_drh()\fR in \fIInformix.pm\fR: .Sp .Vb 1 \& DBD::Informix::dr::driver_init($drh); .Ve .Sp and the following code in \fIInformix.xs\fR: .Sp .Vb 6 \& # Initialize the DBD::Informix driver data structure \& void \& driver_init(drh) \& SV *drh \& CODE: \& ST(0) = dbd_ix_dr_driver_init(drh) ? &sv_yes : &sv_no; .Ve .Sp and the code in \fIdbdimp.h\fR declares: .Sp .Vb 1 \& extern int dbd_ix_dr_driver_init(SV *drh); .Ve .Sp and the code in \fIdbdimp.ec\fR (equivalent to \fIdbdimp.c\fR) defines: .Sp .Vb 11 \& /* Formally initialize the DBD::Informix driver structure */ \& int \& dbd_ix_dr_driver(SV *drh) \& { \& D_imp_drh(drh); \& imp_drh\->n_connections = 0; /* No active connections */ \& imp_drh\->current_connection = 0; /* No current connection */ \& imp_drh\->multipleconnections = (ESQLC_VERSION >= 600) ? True : False; \& dbd_ix_link_newhead(&imp_drh\->head); /* Empty linked list of connections */ \& return 1; \& } .Ve .Sp \&\fBDBD::Oracle\fR has a similar requirement but gets around it by checking whether the private data part of the driver handle is all zeroed out, rather than add extra functions. .PP Now let's take a closer look at an excerpt from \fIOracle.pm\fR (revised heavily to remove idiosyncrasies) as an example, ignoring things that were already discussed for pure Perl drivers. .PP \fIThe connect method\fR .IX Subsection "The connect method" .PP The connect method is the database handle constructor. You could write either of two versions of this method: either one which takes connection attributes (new code) and one which ignores them (old code only). .PP If you ignore the connection attributes, then you omit all mention of the \fR\f(CI$auth\fR\fI\fR variable (which is a reference to a hash of attributes), and the XS system manages the differences for you. .PP .Vb 3 \& sub connect \& { \& my ($drh, $dbname, $user, $auth, $attr) = @_; \& \& # Some database specific verifications, default settings \& # and the like following here. This should only include \& # syntax checks or similar stuff where it\*(Aqs legal to \& # \*(Aqdie\*(Aq in case of errors. \& \& my $dbh = DBI::_new_dbh($drh, { \& \*(AqName\*(Aq => $dbname, \& }) \& or return undef; \& \& # Call the driver\-specific function _login in Driver.xs file which \& # calls the DBMS\-specific function(s) to connect to the database, \& # and populate internal handle data. \& DBD::Driver::db::_login($dbh, $dbname, $user, $auth, $attr) \& or return undef; \& \& $dbh; \& } .Ve .PP This is mostly the same as in the pure Perl case, the exception being the use of the private \f(CW_login()\fR callback, which is the function that will really connect to the database. It is implemented in \&\fIDriver.xst\fR (you should not implement it) and calls \&\f(CWdbd_db_login6()\fR or \f(CW\*(C`dbd_db_login6_sv\*(C'\fR from \fIdbdimp.c\fR. See below for details. .PP If your driver has driver-specific attributes which may be passed in the connect method and hence end up in \f(CW$attr\fR in \f(CW\*(C`dbd_db_login6\*(C'\fR then it is best to delete any you process so DBI does not send them again via STORE after connect. You can do this in C like this: .PP .Vb 2 \& DBD_ATTRIB_DELETE(attr, "my_attribute_name", \& strlen("my_attribute_name")); .Ve .PP However, prior to DBI subversion version 11605 (and fixed post 1.607) DBD_ATTRIB_DELETE segfaulted so if you cannot guarantee the DBI version will be post 1.607 you need to use: .PP .Vb 2 \& hv_delete((HV*)SvRV(attr), "my_attribute_name", \& strlen("my_attribute_name"), G_DISCARD); \& \& *FIX ME* Discuss removing attributes in Perl code. .Ve .PP \fIThe disconnect_all method\fR .IX Subsection "The disconnect_all method" .PP .Vb 1 \& *FIX ME* T.B.S .Ve .PP \fIThe data_sources method\fR .IX Subsection "The data_sources method" .PP If your \f(CWdata_sources()\fR method can be implemented in pure Perl, then do so because it is easier than doing it in XS code (see the section above for pure Perl drivers). .PP If your \f(CWdata_sources()\fR method must call onto compiled functions, then you will need to define \fIdbd_dr_data_sources\fR in your \fIdbdimp.h\fR file, which will trigger \fIDriver.xst\fR (in \fBDBI\fR v1.33 or greater) to generate the XS code that calls your actual C function (see the discussion below for details) and you do not code anything in \fIDriver.pm\fR to handle it. .PP \fIThe prepare method\fR .IX Subsection "The prepare method" .PP The prepare method is the statement handle constructor, and most of it is not new. Like the \f(CWconnect()\fR method, it now has a C callback: .PP .Vb 2 \& package DBD::Driver::db; # ====== DATABASE ====== \& use strict; \& \& sub prepare \& { \& my ($dbh, $statement, $attribs) = @_; \& \& # create a \*(Aqblank\*(Aq sth \& my $sth = DBI::_new_sth($dbh, { \& \*(AqStatement\*(Aq => $statement, \& }) \& or return undef; \& \& # Call the driver\-specific function _prepare in Driver.xs file \& # which calls the DBMS\-specific function(s) to prepare a statement \& # and populate internal handle data. \& DBD::Driver::st::_prepare($sth, $statement, $attribs) \& or return undef; \& $sth; \& } .Ve .PP \fIThe execute method\fR .IX Subsection "The execute method" .PP .Vb 1 \& *FIX ME* T.B.S .Ve .PP \fIThe fetchrow_arrayref method\fR .IX Subsection "The fetchrow_arrayref method" .PP .Vb 1 \& *FIX ME* T.B.S .Ve .PP \fIOther methods?\fR .IX Subsection "Other methods?" .PP .Vb 1 \& *FIX ME* T.B.S .Ve .SS Driver.xs .IX Subsection "Driver.xs" \&\fIDriver.xs\fR should look something like this: .PP .Vb 1 \& #include "Driver.h" \& \& DBISTATE_DECLARE; \& \& INCLUDE: Driver.xsi \& \& MODULE = DBD::Driver PACKAGE = DBD::Driver::dr \& \& /* Non\-standard drh XS methods following here, if any. */ \& /* If none (the usual case), omit the MODULE line above too. */ \& \& MODULE = DBD::Driver PACKAGE = DBD::Driver::db \& \& /* Non\-standard dbh XS methods following here, if any. */ \& /* Currently this includes things like _list_tables from */ \& /* DBD::mSQL and DBD::mysql. */ \& \& MODULE = DBD::Driver PACKAGE = DBD::Driver::st \& \& /* Non\-standard sth XS methods following here, if any. */ \& /* In particular this includes things like _list_fields from */ \& /* DBD::mSQL and DBD::mysql for accessing metadata. */ .Ve .PP Note especially the include of \fIDriver.xsi\fR here: \fBDBI\fR inserts stub functions for almost all private methods here which will typically do much work for you. .PP Wherever you really have to implement something, it will call a private function in \fIdbdimp.c\fR, and this is what you have to implement. .PP You need to set up an extra routine if your driver needs to export constants of its own, analogous to the SQL types available when you say: .PP .Vb 1 \& use DBI qw(:sql_types); \& \& *FIX ME* T.B.S .Ve .SS Driver.h .IX Subsection "Driver.h" \&\fIDriver.h\fR is very simple and the operational contents should look like this: .PP .Vb 2 \& #ifndef DRIVER_H_INCLUDED \& #define DRIVER_H_INCLUDED \& \& #define NEED_DBIXS_VERSION 93 /* 93 for DBI versions 1.00 to 1.51+ */ \& #define PERL_NO_GET_CONTEXT /* if used require DBI 1.51+ */ \& \& #include /* installed by the DBI module */ \& \& #include "dbdimp.h" \& \& #include "dbivport.h" /* see below */ \& \& #include /* installed by the DBI module */ \& \& #endif /* DRIVER_H_INCLUDED */ .Ve .PP The \fIDBIXS.h\fR header defines most of the interesting information that the writer of a driver needs. .PP The file \fIdbd_xsh.h\fR header provides prototype declarations for the C functions that you might decide to implement. Note that you should normally only define one of \f(CWdbd_db_login()\fR, \f(CWdbd_db_login6()\fR or \&\f(CW\*(C`dbd_db_login6_sv\*(C'\fR unless you are intent on supporting really old versions of \fBDBI\fR (prior to \fBDBI\fR 1.06) as well as modern versions. The only standard, \fBDBI\fR\-mandated functions that you need write are those specified in the \fIdbd_xsh.h\fR header. You might also add extra driver-specific functions in \fIDriver.xs\fR. .PP The \fIdbivport.h\fR file should be \fIcopied\fR from the latest \fBDBI\fR release into your distribution each time you modify your driver. Its job is to allow you to enhance your code to work with the latest \fBDBI\fR API while still allowing your driver to be compiled and used with older versions of the \fBDBI\fR (for example, when the \f(CWDBIh_SET_ERR_CHAR()\fR macro was added to \fBDBI\fR 1.41, an emulation of it was added to \fIdbivport.h\fR). This makes users happy and your life easier. Always read the notes in \fIdbivport.h\fR to check for any limitations in the emulation that you should be aware of. .PP With \fBDBI\fR v1.51 or better I recommend that the driver defines \&\fIPERL_NO_GET_CONTEXT\fR before \fIDBIXS.h\fR is included. This can significantly improve efficiency when running under a thread enabled perl. (Remember that the standard perl in most Linux distributions is built with threads enabled. So is ActiveState perl for Windows, and perl built for Apache mod_perl2.) If you do this there are some things to keep in mind: .IP \(bu 4 If \fIPERL_NO_GET_CONTEXT\fR is defined, then every function that calls the Perl API will need to start out with a \f(CW\*(C`dTHX;\*(C'\fR declaration. .IP \(bu 4 You'll know which functions need this, because the C compiler will complain that the undeclared identifier \f(CW\*(C`my_perl\*(C'\fR is used if \fIand only if\fR the perl you are using to develop and test your driver has threads enabled. .IP \(bu 4 If you don't remember to test with a thread-enabled perl before making a release it's likely that you'll get failure reports from users who are. .IP \(bu 4 For driver private functions it is possible to gain even more efficiency by replacing \f(CW\*(C`dTHX;\*(C'\fR with \f(CW\*(C`pTHX_\*(C'\fR prepended to the parameter list and then \f(CW\*(C`aTHX_\*(C'\fR prepended to the argument list where the function is called. .PP See "How multiple interpreters and concurrency are supported" in perlguts for additional information about \fIPERL_NO_GET_CONTEXT\fR. .SS "Implementation header dbdimp.h" .IX Subsection "Implementation header dbdimp.h" This header file has two jobs: .PP First it defines data structures for your private part of the handles. Note that the DBI provides many common fields for you. For example the statement handle (imp_sth) already has a row_count field with an IV type that accessed via the DBIc_ROW_COUNT(imp_sth) macro. Using this is strongly recommended as it's built in to some DBI internals so the DBI can 'just work' in more cases and you'll have less driver-specific code to write. Study DBIXS.h to see what's included with each type of handle. .PP Second it defines macros that rename the generic names like \&\f(CWdbd_db_login()\fR to database specific names like \f(CWora_db_login()\fR. This avoids name clashes and enables use of different drivers when you work with a statically linked perl. .PP It also will have the important task of disabling XS methods that you don't want to implement. .PP Finally, the macros will also be used to select alternate implementations of some functions. For example, the \f(CWdbd_db_login()\fR function is not passed the attribute hash. .PP Since \fBDBI\fR v1.06, if a \f(CWdbd_db_login6()\fR macro is defined (for a function with 6 arguments), it will be used instead with the attribute hash passed as the sixth argument. .PP Since \fBDBI\fR post v1.607, if a \f(CWdbd_db_login6_sv()\fR macro is defined (for a function like dbd_db_login6 but with scalar pointers for the dbname, username and password), it will be used instead. This will allow your login6 function to see if there are any Unicode characters in the dbname. .PP Similarly defining dbd_db_do4_iv is preferred over dbd_db_do4, dbd_st_rows_iv over dbd_st_rows, and dbd_st_execute_iv over dbd_st_execute. The *_iv forms are declared to return the IV type instead of an int. .PP People used to just pick Oracle's \fIdbdimp.c\fR and use the same names, structures and types. I strongly recommend against that. At first glance this saves time, but your implementation will be less readable. It was just hell when I had to separate \fBDBI\fR specific parts, Oracle specific parts, mSQL specific parts and mysql specific parts in \fBDBD::mysql\fR's \&\fIdbdimp.h\fR and \fIdbdimp.c\fR. (\fBDBD::mysql\fR was a port of \fBDBD::mSQL\fR which was based on \fBDBD::Oracle\fR.) [Seconded, based on the experience taking \fBDBD::Informix\fR apart, even though the version inherited in 1996 was only based on \fBDBD::Oracle\fR.] .PP This part of the driver is \fIyour exclusive part\fR. Rewrite it from scratch, so it will be clean and short: in other words, a better piece of code. (Of course keep an eye on other people's work.) .PP .Vb 4 \& struct imp_drh_st { \& dbih_drc_t com; /* MUST be first element in structure */ \& /* Insert your driver handle attributes here */ \& }; \& \& struct imp_dbh_st { \& dbih_dbc_t com; /* MUST be first element in structure */ \& /* Insert your database handle attributes here */ \& }; \& \& struct imp_sth_st { \& dbih_stc_t com; /* MUST be first element in structure */ \& /* Insert your statement handle attributes here */ \& }; \& \& /* Rename functions for avoiding name clashes; prototypes are */ \& /* in dbd_xsh.h */ \& #define dbd_init drv_dr_init \& #define dbd_db_login6_sv drv_db_login_sv \& #define dbd_db_do drv_db_do \& ... many more here ... .Ve .PP These structures implement your private part of the handles. .PP You \fIhave\fR to use the name \f(CW\*(C`imp_dbh_{dr|db|st}\*(C'\fR and the first field \&\fImust\fR be of type \fIdbih_drc_t|_dbc_t|_stc_t\fR and \fImust\fR be called \&\f(CW\*(C`com\*(C'\fR. .PP You should never access these fields directly, except by using the \&\fR\f(BIDBIc_xxx()\fR\fI\fR macros below. .SS "Implementation source dbdimp.c" .IX Subsection "Implementation source dbdimp.c" Conventionally, \fIdbdimp.c\fR is the main implementation file (but \&\fBDBD::Informix\fR calls the file \fIdbdimp.ec\fR). This section includes a short note on each function that is used in the \fIDriver.xsi\fR template and thus \fIhas\fR to be implemented. .PP Of course, you will probably also need to implement other support functions, which should usually be file static if they are placed in \&\fIdbdimp.c\fR. If they are placed in other files, you need to list those files in \fIMakefile.PL\fR (and \fIMANIFEST\fR) to handle them correctly. .PP It is wise to adhere to a namespace convention for your functions to avoid conflicts. For example, for a driver with prefix \fIdrv_\fR, you might call externally visible functions \fIdbd_drv_xxxx\fR. You should also avoid non-constant global variables as much as possible to improve the support for threading. .PP Since Perl requires support for function prototypes (ANSI or ISO or Standard C), you should write your code using function prototypes too. .PP It is possible to use either the unmapped names such as \f(CWdbd_init()\fR or the mapped names such as \f(CWdbd_ix_dr_init()\fR in the \fIdbdimp.c\fR file. \&\fBDBD::Informix\fR uses the mapped names which makes it easier to identify where to look for linkage problems at runtime (which will report errors using the mapped names). .PP Most other drivers, and in particular \fBDBD::Oracle\fR, use the unmapped names in the source code which makes it a little easier to compare code between drivers and eases discussions on the \fIdbi-dev\fR mailing list. The majority of the code fragments here will use the unmapped names. .PP Ultimately, you should provide implementations for most of the functions listed in the \fIdbd_xsh.h\fR header. The exceptions are optional functions (such as \f(CWdbd_st_rows()\fR) and those functions with alternative signatures, such as \f(CW\*(C`dbd_db_login6_sv\*(C'\fR, \&\f(CWdbd_db_login6()\fR and \fR\f(BIdbd_db_login()\fR\fI\fR. Then you should only implement one of the alternatives, and generally the newer one of the alternatives. .PP \fIThe dbd_init method\fR .IX Subsection "The dbd_init method" .PP .Vb 1 \& #include "Driver.h" \& \& DBISTATE_DECLARE; \& \& void dbd_init(dbistate_t* dbistate) \& { \& DBISTATE_INIT; /* Initialize the DBI macros */ \& } .Ve .PP The \f(CWdbd_init()\fR function will be called when your driver is first loaded; the bootstrap command in \f(CWDBD::Driver::dr::driver()\fR triggers this, and the call is generated in the \fIBOOT\fR section of \fIDriver.xst\fR. These statements are needed to allow your driver to use the \fBDBI\fR macros. They will include your private header file \fIdbdimp.h\fR in turn. Note that \fIDBISTATE_INIT\fR requires the name of the argument to \f(CWdbd_init()\fR to be called \f(CWdbistate()\fR. .PP \fIThe dbd_drv_error method\fR .IX Subsection "The dbd_drv_error method" .PP You need a function to record errors so \fBDBI\fR can access them properly. You can call it whatever you like, but we'll call it \f(CWdbd_drv_error()\fR here. .PP The argument list depends on your database software; different systems provide different ways to get at error information. .PP .Vb 2 \& static void dbd_drv_error(SV *h, int rc, const char *what) \& { .Ve .PP Note that \fIh\fR is a generic handle, may it be a driver handle, a database or a statement handle. .PP .Vb 1 \& D_imp_xxh(h); .Ve .PP This macro will declare and initialize a variable \fIimp_xxh\fR with a pointer to your private handle pointer. You may cast this to to \fIimp_drh_t\fR, \fIimp_dbh_t\fR or \fIimp_sth_t\fR. .PP To record the error correctly, equivalent to the \f(CWset_err()\fR method, use one of the \f(CWDBIh_SET_ERR_CHAR(...)\fR or \f(CWDBIh_SET_ERR_SV(...)\fR macros, which were added in \fBDBI\fR 1.41: .PP .Vb 2 \& DBIh_SET_ERR_SV(h, imp_xxh, err, errstr, state, method); \& DBIh_SET_ERR_CHAR(h, imp_xxh, err_c, err_i, errstr, state, method); .Ve .PP For \f(CW\*(C`DBIh_SET_ERR_SV\*(C'\fR the \fIerr\fR, \fIerrstr\fR, \fIstate\fR, and \fImethod\fR parameters are \f(CW\*(C`SV*\*(C'\fR (use &sv_undef instead of NULL). .PP For \f(CW\*(C`DBIh_SET_ERR_CHAR\*(C'\fR the \fIerr_c\fR, \fIerrstr\fR, \fIstate\fR, \fImethod\fR parameters are \f(CW\*(C`char*\*(C'\fR. .PP The \fIerr_i\fR parameter is an \f(CW\*(C`IV\*(C'\fR that's used instead of \fIerr_c\fR if \&\fIerr_c\fR is \f(CW\*(C`Null\*(C'\fR. .PP The \fImethod\fR parameter can be ignored. .PP The \f(CW\*(C`DBIh_SET_ERR_CHAR\*(C'\fR macro is usually the simplest to use when you just have an integer error code and an error message string: .PP .Vb 1 \& DBIh_SET_ERR_CHAR(h, imp_xxh, Nullch, rc, what, Nullch, Nullch); .Ve .PP As you can see, any parameters that aren't relevant to you can be \f(CW\*(C`Null\*(C'\fR. .PP To make drivers compatible with \fBDBI\fR < 1.41 you should be using \fIdbivport.h\fR as described in "Driver.h" above. .PP The (obsolete) macros such as \f(CW\*(C`DBIh_EVENT2\*(C'\fR should be removed from drivers. .PP The names \f(CW\*(C`dbis\*(C'\fR and \f(CW\*(C`DBIS\*(C'\fR, which were used in previous versions of this document, should be replaced with the \f(CWDBIc_DBISTATE(imp_xxh)\fR macro. .PP The name \f(CW\*(C`DBILOGFP\*(C'\fR, which was also used in previous versions of this document, should be replaced by \f(CWDBIc_LOGPIO(imp_xxh)\fR. .PP Your code should not call the C \f(CW\*(C`\*(C'\fR I/O functions; you should use \f(CWPerlIO_printf()\fR as shown: .PP .Vb 3 \& if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) \& PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar %s: %s\en", \& foo, neatsvpv(errstr,0)); .Ve .PP That's the first time we see how tracing works within a \fBDBI\fR driver. Make use of this as often as you can, but don't output anything at a trace level less than 3. Levels 1 and 2 are reserved for the \fBDBI\fR. .PP You can define up to 8 private trace flags using the top 8 bits of \f(CWDBIc_TRACE_FLAGS(imp)\fR, that is: \f(CW0xFF000000\fR. See the \&\f(CWparse_trace_flag()\fR method elsewhere in this document. .PP \fIThe dbd_dr_data_sources method\fR .IX Subsection "The dbd_dr_data_sources method" .PP This method is optional; the support for it was added in \fBDBI\fR v1.33. .PP As noted in the discussion of \fIDriver.pm\fR, if the data sources can be determined by pure Perl code, do it that way. If, as in \&\fBDBD::Informix\fR, the information is obtained by a C function call, then you need to define a function that matches the prototype: .PP .Vb 1 \& extern AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attrs); .Ve .PP An outline implementation for \fBDBD::Informix\fR follows, assuming that the \&\f(CWsqgetdbs()\fR function call shown will return up to 100 databases names, with the pointers to each name in the array dbsname and the name strings themselves being stores in dbsarea. .PP .Vb 7 \& AV *dbd_dr_data_sources(SV *drh, imp_drh_t *imp_drh, SV *attr) \& { \& int ndbs; \& int i; \& char *dbsname[100]; \& char dbsarea[10000]; \& AV *av = Nullav; \& \& if (sqgetdbs(&ndbs, dbsname, 100, dbsarea, sizeof(dbsarea)) == 0) \& { \& av = NewAV(); \& av_extend(av, (I32)ndbs); \& sv_2mortal((SV *)av); \& for (i = 0; i < ndbs; i++) \& av_store(av, i, newSVpvf("dbi:Informix:%s", dbsname[i])); \& } \& return(av); \& } .Ve .PP The actual \fBDBD::Informix\fR implementation has a number of extra lines of code, logs function entry and exit, reports the error from \f(CWsqgetdbs()\fR, and uses \f(CW\*(C`#define\*(C'\fR'd constants for the array sizes. .PP \fIThe dbd_db_login6 method\fR .IX Subsection "The dbd_db_login6 method" .PP .Vb 2 \& int dbd_db_login6_sv(SV* dbh, imp_dbh_t* imp_dbh, SV* dbname, \& SV* user, SV* auth, SV *attr); \& \& or \& \& int dbd_db_login6(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, \& char* user, char* auth, SV *attr); .Ve .PP This function will really connect to the database. The argument \fIdbh\fR is the database handle. \fIimp_dbh\fR is the pointer to the handles private data, as is \fIimp_xxx\fR in \f(CWdbd_drv_error()\fR above. The arguments \&\fIdbname\fR, \fIuser\fR, \fIauth\fR and \fIattr\fR correspond to the arguments of the driver handle's \f(CWconnect()\fR method. .PP You will quite often use database specific attributes here, that are specified in the DSN. I recommend you parse the DSN (using Perl) within the \f(CWconnect()\fR method and pass the segments of the DSN via the attributes parameter through \f(CW_login()\fR to \f(CWdbd_db_login6()\fR. .PP Here's how you fetch them; as an example we use \fIhostname\fR attribute, which can be up to 12 characters long excluding null terminator: .PP .Vb 3 \& SV** svp; \& STRLEN len; \& char* hostname; \& \& if ( (svp = DBD_ATTRIB_GET_SVP(attr, "drv_hostname", 12)) && SvTRUE(*svp)) { \& hostname = SvPV(*svp, len); \& DBD_ATTRIB_DELETE(attr, "drv_hostname", 12); /* avoid later STORE */ \& } else { \& hostname = "localhost"; \& } .Ve .PP If you handle any driver specific attributes in the dbd_db_login6 method you probably want to delete them from \f(CW\*(C`attr\*(C'\fR (as above with DBD_ATTRIB_DELETE). If you don't delete your handled attributes DBI will call \f(CW\*(C`STORE\*(C'\fR for each attribute after the connect/login and this is at best redundant for attributes you have already processed. .PP \&\fBNote: Until revision 11605 (post DBI 1.607), there was a problem with DBD_ATTRIBUTE_DELETE so unless you require a DBI version after 1.607 you need to replace each DBD_ATTRIBUTE_DELETE call with:\fR .PP .Vb 1 \& hv_delete((HV*)SvRV(attr), key, key_len, G_DISCARD) .Ve .PP Note that you can also obtain standard attributes such as \fIAutoCommit\fR and \&\fIChopBlanks\fR from the attributes parameter, using \f(CW\*(C`DBD_ATTRIB_GET_IV\*(C'\fR for integer attributes. .PP If, for example, your database does not support transactions but \&\fIAutoCommit\fR is set off (requesting transaction support), then you can emulate a 'failure to connect'. .PP Now you should really connect to the database. In general, if the connection fails, it is best to ensure that all allocated resources are released so that the handle does not need to be destroyed separately. If you are successful (and possibly even if you fail but you have allocated some resources), you should use the following macros: .PP .Vb 1 \& DBIc_IMPSET_on(imp_dbh); .Ve .PP This indicates that the driver (implementor) has allocated resources in the \fIimp_dbh\fR structure and that the implementors private \f(CWdbd_db_destroy()\fR function should be called when the handle is destroyed. .PP .Vb 1 \& DBIc_ACTIVE_on(imp_dbh); .Ve .PP This indicates that the handle has an active connection to the server and that the \f(CWdbd_db_disconnect()\fR function should be called before the handle is destroyed. .PP Note that if you do need to fail, you should report errors via the \fIdrh\fR or \fIimp_drh\fR rather than via \fIdbh\fR or \fIimp_dbh\fR because \fIimp_dbh\fR will be destroyed by the failure, so errors recorded in that handle will not be visible to \fBDBI\fR, and hence not the user either. .PP Note too, that the function is passed \fIdbh\fR and \fIimp_dbh\fR, and there is a macro \f(CW\*(C`D_imp_drh_from_dbh\*(C'\fR which can recover the \fIimp_drh\fR from the \fIimp_dbh\fR. However, there is no \fBDBI\fR macro to provide you with the \&\fIdrh\fR given either the \fIimp_dbh\fR or the \fIdbh\fR or the \fIimp_drh\fR (and there's no way to recover the \fIdbh\fR given just the \fIimp_dbh\fR). .PP This suggests that, despite the above notes about \f(CWdbd_drv_error()\fR taking an \f(CW\*(C`SV *\*(C'\fR, it may be better to have two error routines, one taking \fIimp_dbh\fR and one taking \fIimp_drh\fR instead. With care, you can factor most of the formatting code out so that these are small routines calling a common error formatter. See the code in \fBDBD::Informix\fR 1.05.00 for more information. .PP The \f(CWdbd_db_login6()\fR function should return \fITRUE\fR for success, \&\fIFALSE\fR otherwise. .PP Drivers implemented long ago may define the five-argument function \&\f(CWdbd_db_login()\fR instead of \f(CWdbd_db_login6()\fR. The missing argument is the attributes. There are ways to work around the missing attributes, but they are ungainly; it is much better to use the 6\-argument form. Even later drivers will use \f(CWdbd_db_login6_sv()\fR which provides the dbname, username and password as SVs. .PP \fIThe dbd_db_commit and dbd_db_rollback methods\fR .IX Subsection "The dbd_db_commit and dbd_db_rollback methods" .PP .Vb 2 \& int dbd_db_commit(SV *dbh, imp_dbh_t *imp_dbh); \& int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh); .Ve .PP These are used for commit and rollback. They should return \fITRUE\fR for success, \fIFALSE\fR for error. .PP The arguments \fIdbh\fR and \fIimp_dbh\fR are the same as for \f(CWdbd_db_login6()\fR above; I will omit describing them in what follows, as they appear always. .PP These functions should return \fITRUE\fR for success, \fIFALSE\fR otherwise. .PP \fIThe dbd_db_disconnect method\fR .IX Subsection "The dbd_db_disconnect method" .PP This is your private part of the \f(CWdisconnect()\fR method. Any \fIdbh\fR with the \fIACTIVE\fR flag on must be disconnected. (Note that you have to set it in \f(CWdbd_db_connect()\fR above.) .PP .Vb 1 \& int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh); .Ve .PP The database handle will return \fITRUE\fR for success, \fIFALSE\fR otherwise. In any case it should do a: .PP .Vb 1 \& DBIc_ACTIVE_off(imp_dbh); .Ve .PP before returning so \fBDBI\fR knows that \f(CWdbd_db_disconnect()\fR was executed. .PP Note that there's nothing to stop a \fIdbh\fR being \fIdisconnected\fR while it still have active children. If your database API reacts badly to trying to use an \fIsth\fR in this situation then you'll need to add code like this to all \fIsth\fR methods: .PP .Vb 2 \& if (!DBIc_ACTIVE(DBIc_PARENT_COM(imp_sth))) \& return 0; .Ve .PP Alternatively, you can add code to your driver to keep explicit track of the statement handles that exist for each database handle and arrange to destroy those handles before disconnecting from the database. There is code to do this in \fBDBD::Informix\fR. Similar comments apply to the driver handle keeping track of all the database handles. .PP Note that the code which destroys the subordinate handles should only release the associated database resources and mark the handles inactive; it does not attempt to free the actual handle structures. .PP This function should return \fITRUE\fR for success, \fIFALSE\fR otherwise, but it is not clear what anything can do about a failure. .PP \fIThe dbd_db_discon_all method\fR .IX Subsection "The dbd_db_discon_all method" .PP .Vb 1 \& int dbd_discon_all (SV *drh, imp_drh_t *imp_drh); .Ve .PP This function may be called at shutdown time. It should make best-efforts to disconnect all database handles \- if possible. Some databases don't support that, in which case you can do nothing but return 'success'. .PP This function should return \fITRUE\fR for success, \fIFALSE\fR otherwise, but it is not clear what anything can do about a failure. .PP \fIThe dbd_db_destroy method\fR .IX Subsection "The dbd_db_destroy method" .PP This is your private part of the database handle destructor. Any \fIdbh\fR with the \fIIMPSET\fR flag on must be destroyed, so that you can safely free resources. (Note that you have to set it in \f(CWdbd_db_connect()\fR above.) .PP .Vb 4 \& void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) \& { \& DBIc_IMPSET_off(imp_dbh); \& } .Ve .PP The \fBDBI\fR \fIDriver.xst\fR code will have called \f(CWdbd_db_disconnect()\fR for you, if the handle is still 'active', before calling \f(CWdbd_db_destroy()\fR. .PP Before returning the function must switch \fIIMPSET\fR to off, so \fBDBI\fR knows that the destructor was called. .PP A \fBDBI\fR handle doesn't keep references to its children. But children do keep references to their parents. So a database handle won't be \&\f(CW\*(C`DESTROY\*(C'\fR'd until all its children have been \f(CW\*(C`DESTROY\*(C'\fR'd. .PP \fIThe dbd_db_STORE_attrib method\fR .IX Subsection "The dbd_db_STORE_attrib method" .PP This function handles .PP .Vb 1 \& $dbh\->{$key} = $value; .Ve .PP Its prototype is: .PP .Vb 2 \& int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv, \& SV* valuesv); .Ve .PP You do not handle all attributes; on the contrary, you should not handle \&\fBDBI\fR attributes here: leave this to \fBDBI\fR. (There are two exceptions, \&\fIAutoCommit\fR and \fIChopBlanks\fR, which you should care about.) .PP The return value is \fITRUE\fR if you have handled the attribute or \fIFALSE\fR otherwise. If you are handling an attribute and something fails, you should call \f(CWdbd_drv_error()\fR, so \fBDBI\fR can raise exceptions, if desired. If \f(CWdbd_drv_error()\fR returns, however, you have a problem: the user will never know about the error, because he typically will not check \&\f(CW\*(C`$dbh\->errstr()\*(C'\fR. .PP I cannot recommend a general way of going on, if \f(CWdbd_drv_error()\fR returns, but there are examples where even the \fBDBI\fR specification expects that you \f(CWcroak()\fR. (See the \fIAutoCommit\fR method in DBI.) .PP If you have to store attributes, you should either use your private data structure \fIimp_xxx\fR, the handle hash (via \f(CW\*(C`(HV*)SvRV(dbh)\*(C'\fR), or use the private \fIimp_data\fR. .PP The first is best for internal C values like integers or pointers and where speed is important within the driver. The handle hash is best for values the user may want to get/set via driver-specific attributes. The private \fIimp_data\fR is an additional \f(CW\*(C`SV\*(C'\fR attached to the handle. You could think of it as an unnamed handle attribute. It's not normally used. .PP \fIThe dbd_db_FETCH_attrib method\fR .IX Subsection "The dbd_db_FETCH_attrib method" .PP This is the counterpart of \f(CWdbd_db_STORE_attrib()\fR, needed for: .PP .Vb 1 \& $value = $dbh\->{$key}; .Ve .PP Its prototype is: .PP .Vb 1 \& SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv); .Ve .PP Unlike all previous methods this returns an \f(CW\*(C`SV\*(C'\fR with the value. Note that you should normally execute \f(CWsv_2mortal()\fR, if you return a nonconstant value. (Constant values are \f(CW&sv_undef\fR, \f(CW&sv_no\fR and \f(CW&sv_yes\fR.) .PP Note, that \fBDBI\fR implements a caching algorithm for attribute values. If you think, that an attribute may be fetched, you store it in the \&\fIdbh\fR itself: .PP .Vb 2 \& if (cacheit) /* cache value for later DBI \*(Aqquick\*(Aq fetch? */ \& hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0); .Ve .PP \fIThe dbd_st_prepare method\fR .IX Subsection "The dbd_st_prepare method" .PP This is the private part of the \f(CWprepare()\fR method. Note that you \&\fBmust not\fR really execute the statement here. You may, however, preparse and validate the statement, or do similar things. .PP .Vb 2 \& int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement, \& SV* attribs); .Ve .PP A typical, simple, possibility is to do nothing and rely on the perl \&\f(CWprepare()\fR code that set the \fIStatement\fR attribute on the handle. This attribute can then be used by \f(CWdbd_st_execute()\fR. .PP If the driver supports placeholders then the \fINUM_OF_PARAMS\fR attribute must be set correctly by \f(CWdbd_st_prepare()\fR: .PP .Vb 1 \& DBIc_NUM_PARAMS(imp_sth) = ... .Ve .PP If you can, you should also setup attributes like \fINUM_OF_FIELDS\fR, \fINAME\fR, etc. here, but \fBDBI\fR doesn't require that \- they can be deferred until \&\fBexecute()\fR is called. However, if you do, document it. .PP In any case you should set the \fIIMPSET\fR flag, as you did in \&\f(CWdbd_db_connect()\fR above: .PP .Vb 1 \& DBIc_IMPSET_on(imp_sth); .Ve .PP \fIThe dbd_st_execute method\fR .IX Subsection "The dbd_st_execute method" .PP This is where a statement will really be executed. .PP .Vb 1 \& int dbd_st_execute(SV* sth, imp_sth_t* imp_sth); .Ve .PP \&\f(CW\*(C`dbd_st_execute\*(C'\fR should return \-2 for any error, \-1 if the number of rows affected is unknown else it should be the number of affected (updated, inserted) rows. .PP Note that you must be aware a statement may be executed repeatedly. Also, you should not expect that \f(CWfinish()\fR will be called between two executions, so you might need code, like the following, near the start of the function: .PP .Vb 2 \& if (DBIc_ACTIVE(imp_sth)) \& dbd_st_finish(h, imp_sth); .Ve .PP If your driver supports the binding of parameters (it should!), but the database doesn't, you must do it here. This can be done as follows: .PP .Vb 4 \& SV *svp; \& char* statement = DBD_ATTRIB_GET_PV(h, "Statement", 9, svp, ""); \& int numParam = DBIc_NUM_PARAMS(imp_sth); \& int i; \& \& for (i = 0; i < numParam; i++) \& { \& char* value = dbd_db_get_param(sth, imp_sth, i); \& /* It is your drivers task to implement dbd_db_get_param, */ \& /* it must be setup as a counterpart of dbd_bind_ph. */ \& /* Look for \*(Aq?\*(Aq and replace it with \*(Aqvalue\*(Aq. Difficult */ \& /* task, note that you may have question marks inside */ \& /* quotes and comments the like ... :\-( */ \& /* See DBD::mysql for an example. (Don\*(Aqt look too deep into */ \& /* the example, you will notice where I was lazy ...) */ \& } .Ve .PP The next thing is to really execute the statement. .PP Note that you must set the attributes \fINUM_OF_FIELDS\fR, \fINAME\fR, etc when the statement is successfully executed if the driver has not already done so: they may be used even before a potential \f(CWfetchrow()\fR. In particular you have to tell \fBDBI\fR the number of fields that the statement has, because it will be used by \fBDBI\fR internally. Thus the function will typically ends with: .PP .Vb 4 \& if (isSelectStatement) { \& DBIc_NUM_FIELDS(imp_sth) = numFields; \& DBIc_ACTIVE_on(imp_sth); \& } .Ve .PP It is important that the \fIACTIVE\fR flag only be set for \f(CW\*(C`SELECT\*(C'\fR statements (or any other statements that can return many values from the database using a cursor-like mechanism). See \&\f(CWdbd_db_connect()\fR above for more explanations. .PP There plans for a preparse function to be provided by \fBDBI\fR, but this has not reached fruition yet. Meantime, if you want to know how ugly it can get, try looking at the \&\f(CWdbd_ix_preparse()\fR in \fBDBD::Informix\fR \fIdbdimp.ec\fR and the related functions in \fIiustoken.c\fR and \fIsqltoken.c\fR. .PP \fIThe dbd_st_fetch method\fR .IX Subsection "The dbd_st_fetch method" .PP This function fetches a row of data. The row is stored in in an array, of \f(CW\*(C`SV\*(C'\fR's that \fBDBI\fR prepares for you. This has two advantages: it is fast (you even reuse the \f(CW\*(C`SV\*(C'\fR's, so they don't have to be created after the first \f(CWfetchrow()\fR), and it guarantees that \fBDBI\fR handles \f(CWbind_cols()\fR for you. .PP What you do is the following: .PP .Vb 6 \& AV* av; \& int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS \& is constant for this statement. There are drivers where this is \& not the case! */ \& int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks); \& int i; \& \& if (!fetch_new_row_of_data(...)) { \& ... /* check for error or end\-of\-data */ \& DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */ \& return Nullav; \& } \& /* get the fbav (field buffer array value) for this row */ \& /* it is very important to only call this after you know */ \& /* that you have a row of data to return. */ \& av = DBIc_DBISTATE(imp_sth)\->get_fbav(imp_sth); \& for (i = 0; i < numFields; i++) { \& SV* sv = fetch_a_field(..., i); \& if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) { \& /* Remove white space from end (only) of sv */ \& } \& sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */ \& } \& return av; .Ve .PP There's no need to use a \f(CWfetch_a_field()\fR function returning an \f(CW\*(C`SV*\*(C'\fR. It's more common to use your database API functions to fetch the data as character strings and use code like this: .PP .Vb 1 \& sv_setpvn(AvARRAY(av)[i], char_ptr, char_count); .Ve .PP \&\f(CW\*(C`NULL\*(C'\fR values must be returned as \f(CW\*(C`undef\*(C'\fR. You can use code like this: .PP .Vb 1 \& SvOK_off(AvARRAY(av)[i]); .Ve .PP The function returns the \f(CW\*(C`AV\*(C'\fR prepared by \fBDBI\fR for success or \f(CW\*(C`Nullav\*(C'\fR otherwise. .PP .Vb 3 \& *FIX ME* Discuss what happens when there\*(Aqs no more data to fetch. \& Are errors permitted if another fetch occurs after the first fetch \& that reports no more data. (Permitted, not required.) .Ve .PP If an error occurs which leaves the \fR\f(CI$sth\fR\fI\fR in a state where remaining rows can't be fetched then \fIActive\fR should be turned off before the method returns. .PP \fIThe dbd_st_finish3 method\fR .IX Subsection "The dbd_st_finish3 method" .PP The \f(CW\*(C`$sth\->finish()\*(C'\fR method can be called if the user wishes to indicate that no more rows will be fetched even if the database has more rows to offer, and the \fBDBI\fR code can call the function when handles are being destroyed. See the \fBDBI\fR specification for more background details. .PP In both circumstances, the \fBDBI\fR code ends up calling the \&\f(CWdbd_st_finish3()\fR method (if you provide a mapping for \&\f(CWdbd_st_finish3()\fR in \fIdbdimp.h\fR), or \f(CWdbd_st_finish()\fR otherwise. The difference is that \f(CWdbd_st_finish3()\fR takes a third argument which is an \f(CW\*(C`int\*(C'\fR with the value 1 if it is being called from a \f(CWdestroy()\fR method and 0 otherwise. .PP Note that \fBDBI\fR v1.32 and earlier test on \f(CWdbd_db_finish3()\fR to call \&\f(CWdbd_st_finish3()\fR; if you provide \f(CWdbd_st_finish3()\fR, either define \&\f(CWdbd_db_finish3()\fR too, or insist on \fBDBI\fR v1.33 or later. .PP All it \fIneeds\fR to do is turn off the \fIActive\fR flag for the \fIsth\fR. It will only be called by \fIDriver.xst\fR code, if the driver has set \fIACTIVE\fR to on for the \fIsth\fR. .PP Outline example: .PP .Vb 8 \& int dbd_st_finish3(SV* sth, imp_sth_t* imp_sth, int from_destroy) { \& if (DBIc_ACTIVE(imp_sth)) \& { \& /* close cursor or equivalent action */ \& DBIc_ACTIVE_off(imp_sth); \& } \& return 1; \& } .Ve .PP The from_destroy parameter is true if \f(CWdbd_st_finish3()\fR is being called from \f(CWDESTROY()\fR \- and so the statement is about to be destroyed. For many drivers there is no point in doing anything more than turning off the \fIActive\fR flag in this case. .PP The function returns \fITRUE\fR for success, \fIFALSE\fR otherwise, but there isn't a lot anyone can do to recover if there is an error. .PP \fIThe dbd_st_destroy method\fR .IX Subsection "The dbd_st_destroy method" .PP This function is the private part of the statement handle destructor. .PP .Vb 4 \& void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth) { \& ... /* any clean\-up that\*(Aqs needed */ \& DBIc_IMPSET_off(imp_sth); /* let DBI know we\*(Aqve done it */ \& } .Ve .PP The \fBDBI\fR \fIDriver.xst\fR code will call \f(CWdbd_st_finish()\fR for you, if the \&\fIsth\fR has the \fIACTIVE\fR flag set, before calling \f(CWdbd_st_destroy()\fR. .PP \fIThe dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods\fR .IX Subsection "The dbd_st_STORE_attrib and dbd_st_FETCH_attrib methods" .PP These functions correspond to \f(CWdbd_db_STORE()\fR and \f(CWdbd_db_FETCH()\fR attrib above, except that they are for statement handles. See above. .PP .Vb 3 \& int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv, \& SV* valuesv); \& SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv); .Ve .PP \fIThe dbd_bind_ph method\fR .IX Subsection "The dbd_bind_ph method" .PP This function is internally used by the \f(CWbind_param()\fR method, the \&\f(CWbind_param_inout()\fR method and by the \fBDBI\fR \fIDriver.xst\fR code if \&\f(CWexecute()\fR is called with any bind parameters. .PP .Vb 3 \& int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param, \& SV *value, IV sql_type, SV *attribs, \& int is_inout, IV maxlen); .Ve .PP The \fIparam\fR argument holds an \f(CW\*(C`IV\*(C'\fR with the parameter number (1, 2, ...). The \fIvalue\fR argument is the parameter value and \fIsql_type\fR is its type. .PP If your driver does not support \f(CWbind_param_inout()\fR then you should ignore \fImaxlen\fR and croak if \fIis_inout\fR is \fITRUE\fR. .PP If your driver \fIdoes\fR support \f(CWbind_param_inout()\fR then you should note that \fIvalue\fR is the \f(CW\*(C`SV\*(C'\fR \fIafter\fR dereferencing the reference passed to \f(CWbind_param_inout()\fR. .PP In drivers of simple databases the function will, for example, store the value in a parameter array and use it later in \f(CWdbd_st_execute()\fR. See the \fBDBD::mysql\fR driver for an example. .PP \fIImplementing bind_param_inout support\fR .IX Subsection "Implementing bind_param_inout support" .PP To provide support for parameters bound by reference rather than by value, the driver must do a number of things. First, and most importantly, it must note the references and stash them in its own driver structure. Secondly, when a value is bound to a column, the driver must discard any previous reference bound to the column. On each execute, the driver must evaluate the references and internally bind the values resulting from the references. This is only applicable if the user writes: .PP .Vb 1 \& $sth\->execute; .Ve .PP If the user writes: .PP .Vb 1 \& $sth\->execute(@values); .Ve .PP then \fBDBI\fR automatically calls the binding code for each element of \&\fR\f(CI@values\fR\fI\fR. These calls are indistinguishable from explicit user calls to \&\f(CWbind_param()\fR. .SS "C/XS version of Makefile.PL" .IX Subsection "C/XS version of Makefile.PL" The \fIMakefile.PL\fR file for a C/XS driver is similar to the code needed for a pure Perl driver, but there are a number of extra bits of information needed by the build system. .PP For example, the attributes list passed to \f(CWWriteMakefile()\fR needs to specify the object files that need to be compiled and built into the shared object (DLL). This is often, but not necessarily, just \&\fIdbdimp.o\fR (unless that should be \fIdbdimp.obj\fR because you're building on MS Windows). .PP Note that you can reliably determine the extension of the object files from the \fR\f(CI$Config\fR\fI{obj_ext}\fR values, and there are many other useful pieces of configuration information lurking in that hash. You get access to it with: .PP .Vb 1 \& use Config; .Ve .SS "Methods which do not need to be written" .IX Subsection "Methods which do not need to be written" The \fBDBI\fR code implements the majority of the methods which are accessed using the notation \f(CW\*(C`DBI\->function()\*(C'\fR, the only exceptions being \&\f(CW\*(C`DBI\->connect()\*(C'\fR and \f(CW\*(C`DBI\->data_sources()\*(C'\fR which require support from the driver. .PP The \fBDBI\fR code implements the following documented driver, database and statement functions which do not need to be written by the \fBDBD\fR driver writer. .ie n .IP $dbh\->\fBdo()\fR 4 .el .IP \f(CW$dbh\fR\->\fBdo()\fR 4 .IX Item "$dbh->do()" The default implementation of this function prepares, executes and destroys the statement. This can be replaced if there is a better way to implement this, such as \f(CW\*(C`EXECUTE IMMEDIATE\*(C'\fR which can sometimes be used if there are no parameters. .ie n .IP $h\->\fBerrstr()\fR 4 .el .IP \f(CW$h\fR\->\fBerrstr()\fR 4 .IX Item "$h->errstr()" .PD 0 .ie n .IP $h\->\fBerr()\fR 4 .el .IP \f(CW$h\fR\->\fBerr()\fR 4 .IX Item "$h->err()" .ie n .IP $h\->\fBstate()\fR 4 .el .IP \f(CW$h\fR\->\fBstate()\fR 4 .IX Item "$h->state()" .ie n .IP $h\->\fBtrace()\fR 4 .el .IP \f(CW$h\fR\->\fBtrace()\fR 4 .IX Item "$h->trace()" .PD The \fBDBD\fR driver does not need to worry about these routines at all. .ie n .IP $h\->{ChopBlanks} 4 .el .IP \f(CW$h\fR\->{ChopBlanks} 4 .IX Item "$h->{ChopBlanks}" This attribute needs to be honored during \f(CWfetch()\fR operations, but does not need to be handled by the attribute handling code. .ie n .IP $h\->{RaiseError} 4 .el .IP \f(CW$h\fR\->{RaiseError} 4 .IX Item "$h->{RaiseError}" The \fBDBD\fR driver does not need to worry about this attribute at all. .ie n .IP $h\->{PrintError} 4 .el .IP \f(CW$h\fR\->{PrintError} 4 .IX Item "$h->{PrintError}" The \fBDBD\fR driver does not need to worry about this attribute at all. .ie n .IP $sth\->\fBbind_col()\fR 4 .el .IP \f(CW$sth\fR\->\fBbind_col()\fR 4 .IX Item "$sth->bind_col()" Assuming the driver uses the \f(CW\*(C`DBIc_DBISTATE(imp_xxh)\->get_fbav()\*(C'\fR function (C drivers, see below), or the \f(CW\*(C`$sth\->_set_fbav($data)\*(C'\fR method (Perl drivers) the driver does not need to do anything about this routine. .ie n .IP $sth\->\fBbind_columns()\fR 4 .el .IP \f(CW$sth\fR\->\fBbind_columns()\fR 4 .IX Item "$sth->bind_columns()" Regardless of whether the driver uses \&\f(CW\*(C`DBIc_DBISTATE(imp_xxh)\->get_fbav()\*(C'\fR, the driver does not need to do anything about this routine as it simply iteratively calls \&\f(CW\*(C`$sth\->bind_col()\*(C'\fR. .PP The \fBDBI\fR code implements a default implementation of the following functions which do not need to be written by the \fBDBD\fR driver writer unless the default implementation is incorrect for the Driver. .ie n .IP $dbh\->\fBquote()\fR 4 .el .IP \f(CW$dbh\fR\->\fBquote()\fR 4 .IX Item "$dbh->quote()" This should only be written if the database does not accept the ANSI SQL standard for quoting strings, with the string enclosed in single quotes and any embedded single quotes replaced by two consecutive single quotes. .Sp For the two argument form of quote, you need to implement the \&\f(CWtype_info()\fR method to provide the information that quote needs. .ie n .IP $dbh\->\fBping()\fR 4 .el .IP \f(CW$dbh\fR\->\fBping()\fR 4 .IX Item "$dbh->ping()" This should be implemented as a simple efficient way to determine whether the connection to the database is still alive. Typically code like this: .Sp .Vb 9 \& sub ping { \& my $dbh = shift; \& $sth = $dbh\->prepare_cached(q{ \& select * from A_TABLE_NAME where 1=0 \& }) or return 0; \& $sth\->execute or return 0; \& $sth\->finish; \& return 1; \& } .Ve .Sp where \fIA_TABLE_NAME\fR is the name of a table that always exists (such as a database system catalogue). .ie n .IP $drh\->default_user 4 .el .IP \f(CW$drh\fR\->default_user 4 .IX Item "$drh->default_user" The default implementation of default_user will get the database username and password fields from \f(CW$ENV{DBI_USER}\fR and \&\f(CW$ENV{DBI_PASS}\fR. You can override this method. It is called as follows: .Sp .Vb 1 \& ($user, $pass) = $drh\->default_user($user, $pass, $attr) .Ve .SH "METADATA METHODS" .IX Header "METADATA METHODS" The exposition above ignores the \fBDBI\fR MetaData methods. The metadata methods are all associated with a database handle. .SS "Using DBI::DBD::Metadata" .IX Subsection "Using DBI::DBD::Metadata" The \fBDBI::DBD::Metadata\fR module is a good semi-automatic way for the developer of a \fBDBD\fR module to write the \f(CWget_info()\fR and \f(CWtype_info()\fR functions quickly and accurately. .PP \fIGenerating the get_info method\fR .IX Subsection "Generating the get_info method" .PP Prior to \fBDBI\fR v1.33, this existed as the method \f(CWwrite_getinfo_pm()\fR in the \fBDBI::DBD\fR module. From \fBDBI\fR v1.33, it exists as the method \&\f(CWwrite_getinfo_pm()\fR in the \fBDBI::DBD::Metadata\fR module. This discussion assumes you have \fBDBI\fR v1.33 or later. .PP You examine the documentation for \f(CWwrite_getinfo_pm()\fR using: .PP .Vb 1 \& perldoc DBI::DBD::Metadata .Ve .PP To use it, you need a Perl \fBDBI\fR driver for your database which implements the \f(CWget_info()\fR method. In practice, this means you need to install \&\fBDBD::ODBC\fR, an ODBC driver manager, and an ODBC driver for your database. .PP With the pre-requisites in place, you might type: .PP .Vb 2 \& perl \-MDBI::DBD::Metadata \-we \e \& "write_getinfo_pm (qw{ dbi:ODBC:foo_db username password Driver })" .Ve .PP The procedure writes to standard output the code that should be added to your \fIDriver.pm\fR file and the code that should be written to \&\fIlib/DBD/Driver/GetInfo.pm\fR. .PP You should review the output to ensure that it is sensible. .PP \fIGenerating the type_info method\fR .IX Subsection "Generating the type_info method" .PP Given the idea of the \f(CWwrite_getinfo_pm()\fR method, it was not hard to devise a parallel method, \f(CWwrite_typeinfo_pm()\fR, which does the analogous job for the \fBDBI\fR \f(CWtype_info_all()\fR metadata method. The \&\f(CWwrite_typeinfo_pm()\fR method was added to \fBDBI\fR v1.33. .PP You examine the documentation for \f(CWwrite_typeinfo_pm()\fR using: .PP .Vb 1 \& perldoc DBI::DBD::Metadata .Ve .PP The setup is exactly analogous to the mechanism described in "Generating the get_info method". .PP With the pre-requisites in place, you might type: .PP .Vb 2 \& perl \-MDBI::DBD::Metadata \-we \e \& "write_typeinfo_pm (qw{ dbi:ODBC:foo_db username password Driver })" .Ve .PP The procedure writes to standard output the code that should be added to your \fIDriver.pm\fR file and the code that should be written to \&\fIlib/DBD/Driver/TypeInfo.pm\fR. .PP You should review the output to ensure that it is sensible. .SS "Writing DBD::Driver::db::get_info" .IX Subsection "Writing DBD::Driver::db::get_info" If you use the \fBDBI::DBD::Metadata\fR module, then the code you need is generated for you. .PP If you decide not to use the \fBDBI::DBD::Metadata\fR module, you should probably borrow the code from a driver that has done so (eg \&\fBDBD::Informix\fR from version 1.05 onwards) and crib the code from there, or look at the code that generates that module and follow that. The method in \fIDriver.pm\fR will be very simple; the method in \&\fIlib/DBD/Driver/GetInfo.pm\fR is not very much more complex unless your DBMS itself is much more complex. .PP Note that some of the \fBDBI\fR utility methods rely on information from the \&\f(CWget_info()\fR method to perform their operations correctly. See, for example, the \f(CWquote_identifier()\fR and quote methods, discussed below. .SS "Writing DBD::Driver::db::type_info_all" .IX Subsection "Writing DBD::Driver::db::type_info_all" If you use the \f(CW\*(C`DBI::DBD::Metadata\*(C'\fR module, then the code you need is generated for you. .PP If you decide not to use the \f(CW\*(C`DBI::DBD::Metadata\*(C'\fR module, you should probably borrow the code from a driver that has done so (eg \&\f(CW\*(C`DBD::Informix\*(C'\fR from version 1.05 onwards) and crib the code from there, or look at the code that generates that module and follow that. The method in \fIDriver.pm\fR will be very simple; the method in \&\fIlib/DBD/Driver/TypeInfo.pm\fR is not very much more complex unless your DBMS itself is much more complex. .SS "Writing DBD::Driver::db::type_info" .IX Subsection "Writing DBD::Driver::db::type_info" The guidelines on writing this method are still not really clear. No sample implementation is available. .SS "Writing DBD::Driver::db::table_info" .IX Subsection "Writing DBD::Driver::db::table_info" .Vb 2 \& *FIX ME* The guidelines on writing this method have not been written yet. \& No sample implementation is available. .Ve .SS "Writing DBD::Driver::db::column_info" .IX Subsection "Writing DBD::Driver::db::column_info" .Vb 2 \& *FIX ME* The guidelines on writing this method have not been written yet. \& No sample implementation is available. .Ve .SS "Writing DBD::Driver::db::primary_key_info" .IX Subsection "Writing DBD::Driver::db::primary_key_info" .Vb 2 \& *FIX ME* The guidelines on writing this method have not been written yet. \& No sample implementation is available. .Ve .SS "Writing DBD::Driver::db::primary_key" .IX Subsection "Writing DBD::Driver::db::primary_key" .Vb 2 \& *FIX ME* The guidelines on writing this method have not been written yet. \& No sample implementation is available. .Ve .SS "Writing DBD::Driver::db::foreign_key_info" .IX Subsection "Writing DBD::Driver::db::foreign_key_info" .Vb 2 \& *FIX ME* The guidelines on writing this method have not been written yet. \& No sample implementation is available. .Ve .SS "Writing DBD::Driver::db::tables" .IX Subsection "Writing DBD::Driver::db::tables" This method generates an array of names in a format suitable for being embedded in SQL statements in places where a table name is expected. .PP If your database hews close enough to the SQL standard or if you have implemented an appropriate \f(CWtable_info()\fR function and and the appropriate \&\f(CWquote_identifier()\fR function, then the \fBDBI\fR default version of this method will work for your driver too. .PP Otherwise, you have to write a function yourself, such as: .PP .Vb 12 \& sub tables \& { \& my($dbh, $cat, $sch, $tab, $typ) = @_; \& my(@res); \& my($sth) = $dbh\->table_info($cat, $sch, $tab, $typ); \& my(@arr); \& while (@arr = $sth\->fetchrow_array) \& { \& push @res, $dbh\->quote_identifier($arr[0], $arr[1], $arr[2]); \& } \& return @res; \& } .Ve .PP See also the default implementation in \fIDBI.pm\fR. .SS "Writing DBD::Driver::db::quote" .IX Subsection "Writing DBD::Driver::db::quote" This method takes a value and converts it into a string suitable for embedding in an SQL statement as a string literal. .PP If your DBMS accepts the SQL standard notation for strings (single quotes around the string as a whole with any embedded single quotes doubled up), then you do not need to write this method as \fBDBI\fR provides a default method that does it for you. .PP If your DBMS uses an alternative notation or escape mechanism, then you need to provide an equivalent function. For example, suppose your DBMS used C notation with double quotes around the string and backslashes escaping both double quotes and backslashes themselves. Then you might write the function as: .PP .Vb 6 \& sub quote \& { \& my($dbh, $str) = @_; \& $str =~ s/["\e\e]/\e\e$&/gmo; \& return qq{"$str"}; \& } .Ve .PP Handling newlines and other control characters is left as an exercise for the reader. .PP This sample method ignores the \fR\f(CI$data_type\fR\fI\fR indicator which is the optional second argument to the method. .SS "Writing DBD::Driver::db::quote_identifier" .IX Subsection "Writing DBD::Driver::db::quote_identifier" This method is called to ensure that the name of the given table (or other database object) can be embedded into an SQL statement without danger of misinterpretation. The result string should be usable in the text of an SQL statement as the identifier for a table. .PP If your DBMS accepts the SQL standard notation for quoted identifiers (which uses double quotes around the identifier as a whole, with any embedded double quotes doubled up) and accepts \fI"schema"."identifier"\fR (and \fI"catalog"."schema"."identifier"\fR when a catalog is specified), then you do not need to write this method as \fBDBI\fR provides a default method that does it for you. .PP In fact, even if your DBMS does not handle exactly that notation but you have implemented the \f(CWget_info()\fR method and it gives the correct responses, then it will work for you. If your database is fussier, then you need to implement your own version of the function. .PP For example, \fBDBD::Informix\fR has to deal with an environment variable \&\fIDELIMIDENT\fR. If it is not set, then the DBMS treats names enclosed in double quotes as strings rather than names, which is usually a syntax error. Additionally, the catalog portion of the name is separated from the schema and table by a different delimiter (colon instead of dot), and the catalog portion is never enclosed in quotes. (Fortunately, valid strings for the catalog will never contain weird characters that might need to be escaped, unless you count dots, dashes, slashes and at-signs as weird.) Finally, an Informix database can contain objects that cannot be accessed because they were created by a user with the \&\fIDELIMIDENT\fR environment variable set, but the current user does not have it set. By design choice, the \f(CWquote_identifier()\fR method encloses those identifiers in double quotes anyway, which generally triggers a syntax error, and the metadata methods which generate lists of tables etc omit those identifiers from the result sets. .PP .Vb 10 \& sub quote_identifier \& { \& my($dbh, $cat, $sch, $obj) = @_; \& my($rv) = ""; \& my($qq) = (defined $ENV{DELIMIDENT}) ? \*(Aq"\*(Aq : \*(Aq\*(Aq; \& $rv .= qq{$cat:} if (defined $cat); \& if (defined $sch) \& { \& if ($sch !~ m/^\ew+$/o) \& { \& $qq = \*(Aq"\*(Aq; \& $sch =~ s/$qq/$qq$qq/gm; \& } \& $rv .= qq{$qq$sch$qq.}; \& } \& if (defined $obj) \& { \& if ($obj !~ m/^\ew+$/o) \& { \& $qq = \*(Aq"\*(Aq; \& $obj =~ s/$qq/$qq$qq/gm; \& } \& $rv .= qq{$qq$obj$qq}; \& } \& return $rv; \& } .Ve .PP Handling newlines and other control characters is left as an exercise for the reader. .PP Note that there is an optional fourth parameter to this function which is a reference to a hash of attributes; this sample implementation ignores that. .PP This sample implementation also ignores the single-argument variant of the method. .SH TRACING .IX Header "TRACING" Tracing in DBI is controlled with a combination of a trace level and a set of flags which together are known as the trace settings. The trace settings are stored in a single integer and divided into levels and flags by a set of masks (\f(CW\*(C`DBIc_TRACE_LEVEL_MASK\*(C'\fR and \&\f(CW\*(C`DBIc_TRACE_FLAGS_MASK\*(C'\fR). .PP Each handle has it's own trace settings and so does the DBI. When you call a method the DBI merges the handles settings into its own for the duration of the call: the trace flags of the handle are OR'd into the trace flags of the DBI, and if the handle has a higher trace level then the DBI trace level is raised to match it. The previous DBI trace settings are restored when the called method returns. .SS "Trace Level" .IX Subsection "Trace Level" The trace level is the first 4 bits of the trace settings (masked by \&\f(CW\*(C`DBIc_TRACE_FLAGS_MASK\*(C'\fR) and represents trace levels of 1 to 15. Do not output anything at trace levels less than 3 as they are reserved for DBI. .PP For advice on what to output at each level see "Trace Levels" in DBI. .PP To test for a trace level you can use the \f(CW\*(C`DBIc_TRACE_LEVEL\*(C'\fR macro like this: .PP .Vb 3 \& if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { \& PerlIO_printf(DBIc_LOGPIO(imp_xxh), "foobar"); \& } .Ve .PP Also \fBnote\fR the use of PerlIO_printf which you should always use for tracing and never the C \f(CW\*(C`stdio.h\*(C'\fR I/O functions. .SS "Trace Flags" .IX Subsection "Trace Flags" Trace flags are used to enable tracing of specific activities within the DBI and drivers. The DBI defines some trace flags and drivers can define others. DBI trace flag names begin with a capital letter and driver specific names begin with a lowercase letter. For a list of DBI defined trace flags see "Trace Flags" in DBI. .PP If you want to use private trace flags you'll probably want to be able to set them by name. Drivers are expected to override the parse_trace_flag (note the singular) and check if \f(CW$trace_flag_name\fR is a driver specific trace flags and, if not, then call the DBIs default \&\fBparse_trace_flag()\fR. To do that you'll need to define a \&\fBparse_trace_flag()\fR method like this: .PP .Vb 9 \& sub parse_trace_flag { \& my ($h, $name) = @_; \& return 0x01000000 if $name eq \*(Aqfoo\*(Aq; \& return 0x02000000 if $name eq \*(Aqbar\*(Aq; \& return 0x04000000 if $name eq \*(Aqbaz\*(Aq; \& return 0x08000000 if $name eq \*(Aqboo\*(Aq; \& return 0x10000000 if $name eq \*(Aqbop\*(Aq; \& return $h\->SUPER::parse_trace_flag($name); \& } .Ve .PP All private flag names must be lowercase, and all private flags must be in the top 8 of the 32 bits of \f(CWDBIc_TRACE_FLAGS(imp)\fR i.e., 0xFF000000. .PP If you've defined a \fBparse_trace_flag()\fR method in ::db you'll also want it in ::st, so just alias it in: .PP .Vb 1 \& *parse_trace_flag = \e&DBD::foo:db::parse_trace_flag; .Ve .PP You may want to act on the current 'SQL' trace flag that DBI defines to output SQL prepared/executed as DBI currently does not do SQL tracing. .SS "Trace Macros" .IX Subsection "Trace Macros" Access to the trace level and trace flags is via a set of macros. .PP .Vb 4 \& DBIc_TRACE_SETTINGS(imp) returns the trace settings \& DBIc_TRACE_LEVEL(imp) returns the trace level \& DBIc_TRACE_FLAGS(imp) returns the trace flags \& DBIc_TRACE(imp, flags, flaglevel, level) \& \& e.g., \& \& DBIc_TRACE(imp, 0, 0, 4) \& if level >= 4 \& \& DBIc_TRACE(imp, DBDtf_FOO, 2, 4) \& if tracing DBDtf_FOO & level>=2 or level>=4 \& \& DBIc_TRACE(imp, DBDtf_FOO, 2, 0) \& as above but never trace just due to level .Ve .SH "WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE" .IX Header "WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE" Study \fIOraperl.pm\fR (supplied with \fBDBD::Oracle\fR) and \fIIngperl.pm\fR (supplied with \fBDBD::Ingres\fR) and the corresponding \fIdbdimp.c\fR files for ideas. .PP Note that the emulation code sets \f(CW\*(C`$dbh\->{CompatMode} = 1;\*(C'\fR for each connection so that the internals of the driver can implement behaviour compatible with the old interface when dealing with those handles. .SS "Setting emulation perl variables" .IX Subsection "Setting emulation perl variables" For example, ingperl has a \fR\f(CI$sql_rowcount\fR\fI\fR variable. Rather than try to manually update this in \fIIngperl.pm\fR it can be done faster in C code. In \f(CWdbd_init()\fR: .PP .Vb 1 \& sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI); .Ve .PP In the relevant places do: .PP .Vb 2 \& if (DBIc_COMPAT(imp_sth)) /* only do this for compatibility mode handles */ \& sv_setiv(sql_rowcount, the_row_count); .Ve .SH "OTHER MISCELLANEOUS INFORMATION" .IX Header "OTHER MISCELLANEOUS INFORMATION" .SS "The imp_xyz_t types" .IX Subsection "The imp_xyz_t types" Any handle has a corresponding C structure filled with private data. Some of this data is reserved for use by \fBDBI\fR (except for using the DBIc macros below), some is for you. See the description of the \&\fIdbdimp.h\fR file above for examples. Most functions in \fIdbdimp.c\fR are passed both the handle \f(CW\*(C`xyz\*(C'\fR and a pointer to \f(CW\*(C`imp_xyz\*(C'\fR. In rare cases, however, you may use the following macros: .IP D_imp_dbh(dbh) 4 .IX Item "D_imp_dbh(dbh)" Given a function argument \fIdbh\fR, declare a variable \fIimp_dbh\fR and initialize it with a pointer to the handles private data. Note: This must be a part of the function header, because it declares a variable. .IP D_imp_sth(sth) 4 .IX Item "D_imp_sth(sth)" Likewise for statement handles. .IP D_imp_xxx(h) 4 .IX Item "D_imp_xxx(h)" Given any handle, declare a variable \fIimp_xxx\fR and initialize it with a pointer to the handles private data. It is safe, for example, to cast \fIimp_xxx\fR to \f(CW\*(C`imp_dbh_t*\*(C'\fR, if \f(CW\*(C`DBIc_TYPE(imp_xxx) == DBIt_DB\*(C'\fR. (You can also call \f(CW\*(C`sv_derived_from(h, "DBI::db")\*(C'\fR, but that's much slower.) .IP D_imp_dbh_from_sth 4 .IX Item "D_imp_dbh_from_sth" Given a \fIimp_sth\fR, declare a variable \fIimp_dbh\fR and initialize it with a pointer to the parent database handle's implementors structure. .SS "Using DBIc_IMPSET_on" .IX Subsection "Using DBIc_IMPSET_on" The driver code which initializes a handle should use \f(CWDBIc_IMPSET_on()\fR as soon as its state is such that the cleanup code must be called. When this happens is determined by your driver code. .PP \&\fBFailure to call this can lead to corruption of data structures.\fR .PP For example, \fBDBD::Informix\fR maintains a linked list of database handles in the driver, and within each handle, a linked list of statements. Once a statement is added to the linked list, it is crucial that it is cleaned up (removed from the list). When \fR\f(BIDBIc_IMPSET_on()\fR\fI\fR was being called too late, it was able to cause all sorts of problems. .SS "Using \fBDBIc_is()\fP, \fBDBIc_has()\fP, \fBDBIc_on()\fP and \fBDBIc_off()\fP" .IX Subsection "Using DBIc_is(), DBIc_has(), DBIc_on() and DBIc_off()" Once upon a long time ago, the only way of handling the internal \fBDBI\fR boolean flags/attributes was through macros such as: .PP .Vb 2 \& DBIc_WARN DBIc_WARN_on DBIc_WARN_off \& DBIc_COMPAT DBIc_COMPAT_on DBIc_COMPAT_off .Ve .PP Each of these took an \fIimp_xxh\fR pointer as an argument. .PP Since then, new attributes have been added such as \fIChopBlanks\fR, \&\fIRaiseError\fR and \fIPrintError\fR, and these do not have the full set of macros. The approved method for handling these is now the four macros: .PP .Vb 5 \& DBIc_is(imp, flag) \& DBIc_has(imp, flag) an alias for DBIc_is \& DBIc_on(imp, flag) \& DBIc_off(imp, flag) \& DBIc_set(imp, flag, on) set if on is true, else clear .Ve .PP Consequently, the \f(CW\*(C`DBIc_XXXXX\*(C'\fR family of macros is now mostly deprecated and new drivers should avoid using them, even though the older drivers will probably continue to do so for quite a while yet. However... .PP There is an \fIimportant exception\fR to that. The \fIACTIVE\fR and \fIIMPSET\fR flags should be set via the \f(CWDBIc_ACTIVE_on()\fR and \f(CWDBIc_IMPSET_on()\fR macros, and unset via the \f(CWDBIc_ACTIVE_off()\fR and \f(CWDBIc_IMPSET_off()\fR macros. .SS "Using the \fBget_fbav()\fP method" .IX Subsection "Using the get_fbav() method" \&\fBTHIS IS CRITICAL for C/XS drivers\fR. .PP The \f(CW\*(C`$sth\->bind_col()\*(C'\fR and \f(CW\*(C`$sth\->bind_columns()\*(C'\fR documented in the \fBDBI\fR specification do not have to be implemented by the driver writer because \fBDBI\fR takes care of the details for you. .PP However, the key to ensuring that bound columns work is to call the function \f(CW\*(C`DBIc_DBISTATE(imp_xxh)\->get_fbav()\*(C'\fR in the code which fetches a row of data. .PP This returns an \f(CW\*(C`AV\*(C'\fR, and each element of the \f(CW\*(C`AV\*(C'\fR contains the \f(CW\*(C`SV\*(C'\fR which should be set to contain the returned data. .PP The pure Perl equivalent is the \f(CW\*(C`$sth\->_set_fbav($data)\*(C'\fR method, as described in the part on pure Perl drivers. .SS "Casting strings to Perl types based on a SQL type" .IX Subsection "Casting strings to Perl types based on a SQL type" DBI from 1.611 (and DBIXS_REVISION 13606) defines the sql_type_cast_svpv method which may be used to cast a string representation of a value to a more specific Perl type based on a SQL type. You should consider using this method when processing bound column data as it provides some support for the TYPE bind_col attribute which is rarely used in drivers. .PP .Vb 1 \& int sql_type_cast_svpv(pTHX_ SV *sv, int sql_type, U32 flags, void *v) .Ve .PP \&\f(CW\*(C`sv\*(C'\fR is what you would like cast, \f(CW\*(C`sql_type\*(C'\fR is one of the DBI defined SQL types (e.g., \f(CW\*(C`SQL_INTEGER\*(C'\fR) and \f(CW\*(C`flags\*(C'\fR is a bitmask as follows: .IP DBIstcf_STRICT 4 .IX Item "DBIstcf_STRICT" If set this indicates you want an error state returned if the cast cannot be performed. .IP DBIstcf_DISCARD_STRING 4 .IX Item "DBIstcf_DISCARD_STRING" If set and the pv portion of the \f(CW\*(C`sv\*(C'\fR is cast then this will cause sv's pv to be freed up. .PP sql_type_cast_svpv returns the following states: .PP .Vb 5 \& \-2 sql_type is not handled \- sv not changed \& \-1 sv is undef, sv not changed \& 0 sv could not be cast cleanly and DBIstcf_STRICT was specified \& 1 sv could not be case cleanly and DBIstcf_STRICT was not specified \& 2 sv was cast ok .Ve .PP The current implementation of sql_type_cast_svpv supports \&\f(CW\*(C`SQL_INTEGER\*(C'\fR, \f(CW\*(C`SQL_DOUBLE\*(C'\fR and \f(CW\*(C`SQL_NUMERIC\*(C'\fR. \f(CW\*(C`SQL_INTEGER\*(C'\fR uses sv_2iv and hence may set IV, UV or NV depending on the number. \f(CW\*(C`SQL_DOUBLE\*(C'\fR uses sv_2nv so may set NV and \f(CW\*(C`SQL_NUMERIC\*(C'\fR will set IV or UV or NV. .PP DBIstcf_STRICT should be implemented as the StrictlyTyped attribute and DBIstcf_DISCARD_STRING implemented as the DiscardString attribute to the bind_col method and both default to off. .PP See DBD::Oracle for an example of how this is used. .SH "SUBCLASSING DBI DRIVERS" .IX Header "SUBCLASSING DBI DRIVERS" This is definitely an open subject. It can be done, as demonstrated by the \fBDBD::File\fR driver, but it is not as simple as one might think. .PP (Note that this topic is different from subclassing the \fBDBI\fR. For an example of that, see the \fIt/subclass.t\fR file supplied with the \fBDBI\fR.) .PP The main problem is that the \fIdbh\fR's and \fIsth\fR's that your \f(CWconnect()\fR and \&\f(CWprepare()\fR methods return are not instances of your \fBDBD::Driver::db\fR or \fBDBD::Driver::st\fR packages, they are not even derived from it. Instead they are instances of the \fBDBI::db\fR or \fBDBI::st\fR classes or a derived subclass. Thus, if you write a method \f(CWmymethod()\fR and do a .PP .Vb 1 \& $dbh\->mymethod() .Ve .PP then the autoloader will search for that method in the package \fBDBI::db\fR. Of course you can instead to a .PP .Vb 1 \& $dbh\->func(\*(Aqmymethod\*(Aq) .Ve .PP and that will indeed work, even if \f(CWmymethod()\fR is inherited, but not without additional work. Setting \fR\f(CI@ISA\fR\fI\fR is not sufficient. .SS "Overwriting methods" .IX Subsection "Overwriting methods" The first problem is, that the \f(CWconnect()\fR method has no idea of subclasses. For example, you cannot implement base class and subclass in the same file: The \f(CWinstall_driver()\fR method wants to do a .PP .Vb 1 \& require DBD::Driver; .Ve .PP In particular, your subclass \fBhas\fR to be a separate driver, from the view of \fBDBI\fR, and you cannot share driver handles. .PP Of course that's not much of a problem. You should even be able to inherit the base classes \f(CWconnect()\fR method. But you cannot simply overwrite the method, unless you do something like this, quoted from \fBDBD::CSV\fR: .PP .Vb 2 \& sub connect ($$;$$$) { \& my ($drh, $dbname, $user, $auth, $attr) = @_; \& \& my $this = $drh\->DBD::File::dr::connect($dbname, $user, $auth, $attr); \& if (!exists($this\->{csv_tables})) { \& $this\->{csv_tables} = {}; \& } \& \& $this; \& } .Ve .PP Note that we cannot do a .PP .Vb 1 \& $drh\->SUPER::connect($dbname, $user, $auth, $attr); .Ve .PP as we would usually do in a an OO environment, because \fR\f(CI$drh\fR\fI\fR is an instance of \fBDBI::dr\fR. And note, that the \f(CWconnect()\fR method of \fBDBD::File\fR is able to handle subclass attributes. See the description of Pure Perl drivers above. .PP It is essential that you always call superclass method in the above manner. However, that should do. .SS "Attribute handling" .IX Subsection "Attribute handling" Fortunately the \fBDBI\fR specifications allow a simple, but still performant way of handling attributes. The idea is based on the convention that any driver uses a prefix \fIdriver_\fR for its private methods. Thus it's always clear whether to pass attributes to the super class or not. For example, consider this \f(CWSTORE()\fR method from the \&\fBDBD::CSV\fR class: .PP .Vb 8 \& sub STORE { \& my ($dbh, $attr, $val) = @_; \& if ($attr !~ /^driver_/) { \& return $dbh\->DBD::File::db::STORE($attr, $val); \& } \& if ($attr eq \*(Aqdriver_foo\*(Aq) { \& ... \& } .Ve .SH AUTHORS .IX Header "AUTHORS" Jonathan Leffler (previously ), Jochen Wiedmann , Steffen Goeldner , and Tim Bunce .