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