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