Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / lib / site_perl / 5.8.0 / sun4-solaris / DBI / DBD.pm
CommitLineData
86530b38
AT
1# $Id: DBD.pm,v 10.9 2001/05/29 23:25:55 timbo Exp $
2#
3# Copyright (c) 1997-2000 Jonathan Leffler, Jochen Wiedmann and Tim Bunce
4#
5# You may distribute under the terms of either the GNU General Public
6# License or the Artistic License, as specified in the Perl README file.
7
8=head1 NAME
9
10DBI::DBD - DBD Driver Writer's Guide
11
12=head1 SYNOPSIS
13
14 perldoc DBI::DBD
15
16=head1 VERSION and VOLATILITY
17
18 $Revision: 10.9 $
19 $Date: 2001/05/29 23:25:55 $
20
21This document is a minimal draft which is in need of further work.
22
23The changes will occur both because the DBI specification is changing
24and hence the requirements on DBD drivers change, and because feedback
25from people reading this document will suggest improvements to it.
26
27Please read the DBI documentation first and fully, including the DBI FAQ.
28The reread the DBI specification again as you're reading this. It'll help.
29
30This document is a patchwork of contributions from various authors.
31More contributions (preferably as patches) are very welcome.
32
33=head1 DESCRIPTION
34
35This document is primarily intended to help people writing new
36database drivers for the Perl Database Interface (Perl DBI).
37It may also help others interested in discovering why the internals of
38a DBD driver are written the way they are.
39
40This is a guide. Few (if any) of the statements in it are completely
41authoritative under all possible circumstances. This means you will
42need to use judgement in applying the guidelines in this document.
43If in I<any> doubt at all, please do contact the dbi-dev mailing list
44(details given below) where Tim Bunce and other driver authors can help.
45
46The primary web-site for locating DBI software and information is
47
48 http://www.symbolstone.org/technology/perl/DBI
49
50There are 2 main and one auxilliary mailing lists for people working
51with DBI. The primary lists are dbi-users@isc.org for general users
52of DBI and DBD drivers, and dbi-dev@isc.org mainly for DBD driver
53writers (don't join the dbi-dev list unless you have a good reason).
54The auxilliary list is dbi-announce@isc.org for announcing new
55releases of DBI or DBD drivers.
56
57You can join these lists by accessing the web-site
58L<http://www.isc.org/dbi-lists.html>.
59The lists are closed so you cannot send email to any of the lists
60unless you join the list first.
61
62You should also consider monitoring the comp.lang.perl.* newsgroups.
63
64=head1 BOOK
65
66The definitive book on Perl DBI is 'Programming the Perl DBI: Database
67programming with Perl' by Alligator Descartes and Tim Bunce, published
68by O'Reilly Associates, February 2000, ISBN 1-56592-699-4. Buy it now
69if you have not already done so.
70
71=head1 REGISTERING A NEW DRIVER
72
73Before writing a new driver, it is in your interests to find out
74whether there already is a driver for your database. If there is such
75a driver, it would be much easier to make use of it than to write your
76own!
77
78=head2 Locating drivers
79
80The primary web-site for locating Perl software is
81L<http://www.perl.com/CPAN>.
82You should look under the various modules listings for the software
83you are after.
84Two of the main pages you should look at are:
85
86 http://www.perl.org/CPAN/modules/by-category/07_Database_Interfaces/DBI
87
88 http://www.perl.org/CPAN/modules/by-category/07_Database_Interfaces/DBD
89
90See the DBI docs for information on DBI web sites and mailing lists.
91
92=head2 Registering a new driver
93
94Before going through any official registration process, you will need
95to establish that there is no driver already in the works.
96You'll do that by asking the DBI mailing lists whether there is such a
97driver available, or whether anybody is working on one.
98
99
100=head1 CREATING A NEW DRIVER USING PURE PERL
101
102Writing a pure Perl driver is surprisingly simple. However, there are
103some problems one should be aware of. The best option is of course
104picking up an existing driver and carefully modifying one method
105after the other.
106
107As an example we take a look at the I<DBD::File> driver, a driver for
108accessing plain files as tables, which is part of the I<DBD::CSV>
109package. In what follows I assume the name C<Driver> for your new
110package: The least thing we have to implement are the files
111C<Makefile.PL> and C<Driver.pm>.
112
113
114=head2 Makefile.PL
115
116You typically start with writing C<Makefile.PL>, a Makefile generator.
117The contents of this file are described in detail in the MakeMaker
118man pages, it's definitely a good idea if you start reading them.
119At least you should know about the variables I<CONFIGURE>, I<DEFINED>,
120I<DIR>, I<EXE_FILES>, I<INC>, I<LIBS>, I<LINKTYPE>, I<NAME>, I<OPTIMIZE>,
121I<PL_FILES>, I<VERSION>, I<VERSION_FROM>, I<clean>, I<depend>, I<realclean>
122from the C<ExtUtils::MakeMaker> man page: These are used in almost any
123Makefile.PL. Additionally read the section on I<Overriding MakeMaker Methods>
124and the descriptions of the I<distcheck>, I<disttest> and I<dist> targets:
125They will definitely be useful for you.
126
127Of special importance for DBI drivers is the I<postamble> method from
128the C<ExtUtils::MM_Unix> man page. And for Emacs users I recommend
129the I<libscan> method.
130
131Now an example, I use the word C<Driver> wherever you should insert
132your drivers name:
133
134 # -*- perl -*-
135
136 use DBI 1.03;
137 use DBI::DBD;
138 use ExtUtils::MakeMaker;
139
140 ExtUtils::MakeMaker::WriteMakefile(
141 'NAME' => 'DBD::Driver',
142 'VERSION_FROM' => 'Driver.pm',
143 'INC' => $DBI_INC_DIR,
144 'dist' => { 'SUFFIX' => '.gz',
145 'COMPRESS' => 'gzip -9f' },
146 'realclean' => '*.xsi'
147 );
148
149 package MY;
150 sub postamble { dbd_postamble(@_); }
151 sub libscan {
152 my($self, $path) = @_;
153 ($path =~ /\~$/) ? undef : $path;
154 }
155
156See also L<ExtUtils::MakeMaker(3)>. L<ExtUtils::MM_Unix(3)>.
157
158
159=head2 README file
160
161The README file should describe what the driver is for, the
162pre-requisites for the build process, the actual build process, and how
163to report errors. Users will find ways of breaking the driver build and
164test process which you would never even dreamed to be possible in your
165nightmares. :-) Therefore, you need to write this document defensively
166and precisely. Also, it is in your interests to ensure that your tests
167work as widely as possible. As always, use the README from one of the
168established drivers as a basis for your own.
169
170
171=head2 MANIFEST
172
173The MANIFEST will be used by the Makefile'd dist target to build the
174distribution tar file that is uploaded to CPAN. It should list every
175file that you want to include in your distribution, one per line.
176
177
178=head2 lib/Bundle/DBD/Driver.pm
179
180The CPAN module provides an extremely powerful bundle mechanism that
181allows you to specify pre-requisites for your driver.
182The primary pre-requisite is Bundle::DBI; you may want or need to add
183some more.
184With the bundle set up correctly, the user can type:
185
186 perl -MCPAN -e 'install Bundle::DBD::Driver'
187
188and Perl will download, compile, test and install all the Perl modules
189needed to build your driver.
190
191A suitable skeleton for this file is shown below.
192The prerequisite modules are listed in the CONTENTS section, with the
193official name of the module followed by a dash and an informal name or
194description.
195Listing Bundle::DBI as the main pre-requisite simplifies life.
196Don't forget to list your driver.
197Note that unless the DBMS is itself a Perl module, you cannot list it
198as a pre-requisite in this file.
199You are strongly advised to keep the version of the bundle in sync
200with the version of your driver.
201You might want to add configuration management, copyright, and
202licencing information at the top.
203
204
205 package Bundle::DBD::Driver;
206
207 $VERSION = '0.01';
208
209 1;
210
211 __END__
212
213 =head1 NAME
214
215 Bundle::DBD::Driver - A bundle to install all DBD::Driver related modules
216
217 =head1 SYNOPSIS
218
219 C<perl -MCPAN -e 'install Bundle::DBD::Driver'>
220
221 =head1 CONTENTS
222
223 Bundle::DBI - Bundle for DBI by TIMB (Tim Bunce)
224
225 DBD::Driver - DBD::Driver by YOU (Your Name)
226
227 =head1 DESCRIPTION
228
229 This bundle includes all the modules used by the Perl Database
230 Interface (DBI) driver for Driver (DBD::Driver), assuming the
231 use of DBI version 1.13 or later, created by Tim Bunce.
232
233 If you've not previously used the CPAN module to install any
234 bundles, you will be interrogated during its setup phase.
235 But when you've done it once, it remembers what you told it.
236 You could start by running:
237
238 C<perl -MCPAN -e 'install Bundle::CPAN'>
239
240 =head1 SEE ALSO
241
242 Bundle::DBI
243
244 =head1 AUTHOR
245
246 Your Name E<lt>F<you@yourdomain.com>E<gt>
247
248 =head1 THANKS
249
250 This bundle was created by ripping off Bundle::libnet created by
251 Graham Barr E<lt>F<gbarr@ti.com>E<gt>, and radically simplified
252 with some information from Jochen Wiedmann E<lt>F<joe@ispsoft.de>E<gt>.
253 The template was then included in the DBI::DBD documentation by
254 Jonathan Leffler E<lt>F<jleffler@informix.com>E<gt>.
255
256 =cut
257
258
259=head2 Driver.pm
260
261The Driver.pm file defines the Perl module DBD::Driver for your driver.
262It will define a package DBD::Driver along with some version information,
263some variable definitions, and a function driver() which will have a more
264or less standard structure.
265
266It will also define a package DBD::Driver::dr (with methods connect(),
267data_sources() and disconnect_all()), and a package DBD::Driver::db
268(which will define a function prepare() etc), and a package DBD::Driver::st
269with methods execute(), fetch() and the like.
270
271The Driver.pm file will also contain the documentation specific to
272DBD::Driver in the format used by perldoc.
273
274Now let's take a closer look at an excerpt of File.pm as an example.
275We ignore things that are common to any module (even non-DBI(D) modules)
276or really specific for the DBD::File package.
277
278=over 2
279
280=item The header
281
282 package DBD::File;
283
284 use strict;
285 use vars qw($err $errstr $state $drh);
286
287 $err = 0; # holds error code for DBI::err
288 $errstr = ""; # holds error string for DBI::errstr
289 $sqlstate = ""; # holds SQL state for DBI::state
290
291These variables are used for storing error states and messages.
292However, it is crucial to understand that you must not modify
293them directly; instead use the I<event> method, see below.
294
295 $drh = undef; # holds driver handle once initialized
296
297This is where the driver handle will be stored, once created. Note,
298that you may assume, there's only one handle for your driver.
299
300=item The driver constructor
301
302 sub driver {
303 return $drh if $drh; # already created - return same one
304 my($class, $attr) = @_;
305
306 $class .= "::dr";
307
308 # not a 'my' since we use it above to prevent multiple drivers
309 $drh = DBI::_new_drh($class, {
310 'Name' => 'File',
311 'Version' => $VERSION,
312 'Err' => \$DBD::File::err,
313 'Errstr' => \$DBD::File::errstr,
314 'State' => \$DBD::File::state,
315 'Attribution' => 'DBD::File by Jochen Wiedmann',
316 });
317
318 return $drh;
319 }
320
321The I<driver> method is the driver handle constructor. It's a
322reasonable example of how DBI implements its handles. There are three
323kinds: B<driver handles> (typically stored in C<$drh>, from now on
324called C<drh>), B<database handles> (from now on called C<dbh> or
325C<$dbh>) and B<statement handles>, (from now on called C<sth> or
326C<$sth>).
327
328The prototype of DBI::_new_drh is
329
330 $drh = DBI::_new_drh($class, $attr1, $attr2);
331
332with the following arguments:
333
334=over 4
335
336=item I<$class>
337
338is typically your drivers class, e.g., "DBD::File::dr", passed as first
339argument to the I<driver> method.
340
341=item I<$attr1>
342
343is a hash ref to attributes like I<Name>, I<Version>, I<Err>, I<Errstr>
344I<State> and I<Attributrion>. These are processed and used by DBI, you
345better not make any assumptions on them nor should you add private
346attributes here.
347
348=item I<$attr2>
349
350This is another (optional) hash ref with your private attributes. DBI
351will leave them alone.
352
353=back
354
355The I<DBI::new_drh> method and the I<driver> method
356both return C<undef> for failure (in which case you must look at
357$DBI::err and $DBI::errstr, because you have no driver handle).
358
359
360=item The database handle constructor
361
362The next lines of code look as follows:
363
364 package DBD::Driver::dr; # ====== DRIVER ======
365
366 $DBD::Driver::dr::imp_data_size = 0;
367
368Note that no @ISA is needed here, or for the other DBD::Driver::*
369classes, because the DBI takes care of that for you when the driver is
370loaded.
371
372The database handle constructor is a driver method, thus we have
373to change the namespace.
374
375 sub connect {
376 my($drh, $dbname, $user, $auth, $attr)= @_;
377
378 # Some database specific verifications, default settings
379 # and the like following here. This should only include
380 # syntax checks or similar stuff where it's legal to
381 # 'die' in case of errors.
382
383 # create a 'blank' dbh (call superclass constructor)
384 my $dbh = DBI::_new_dbh($drh, {
385 'Name' => $dbname,
386 'USER' => $user,
387 'CURRENT_USER' => $user,
388 });
389
390 # Process attributes from the DSN; we assume ODBC syntax
391 # here, that is, the DSN looks like var1=val1;...;varN=valN
392
393 my $var;
394 foreach $var (split(/;/, $dbname)) {
395 if ($var =~ /(.*?)=(,*)/) {
396 # Not !!! $dbh->{$var} = $val;
397 $dbh->STORE($var, $val);
398 }
399 }
400 $dbh;
401 }
402
403This is mostly the same as in the I<driver handle constructor> above.
404The arguments are described in the DBI man page. See L<DBI(3)>.
405The constructor is called, returning a database handle. The constructors
406prototype is
407
408 $dbh = DBI::_new_dbh($drh, $attr1, $attr2);
409
410with the same arguments as in the I<driver handle constructor>, the
411exception being C<$class> replaced by C<$drh>.
412
413Note the use of the I<STORE> method for setting the dbh attributes.
414That's because within the driver code, the handle object you have is
415the 'inner' handle of a tied hash, not the outer handle that the
416users of your driver have.
417
418Because you have the inner handle, tie magic doesn't get invoked
419when you get or set values in the hash. This is often very handy for
420speed when you want to get or set simple non-special driver-specific
421attributes.
422
423However, some attribute values, such as those handled by the DBI
424like PrintError, don't actually exist in the hash and must be
425read via $h->FETCH($attrib) and set via $h->STORE($attrib, $value).
426If in any doubt, use these methods.
427
428
429=item Error handling
430
431It is quite likely that something fails in the connect method. With
432DBD::File for example, you might catch an error when setting the
433current directory to something not existant by using the f_dir
434attribute.
435
436To report an error, you use the C<DBI::set_err> function/method:
437
438 $h->DBI::set_err($errcode, $errmsg);
439
440This will ensure that the error is recorded correctly and that
441RaiseError and PrintError etc are handled correctly. Typically you'll
442always use the method instance, aka your method's first argument.
443
444As set_err always returns undef your error handling code can
445usually be simplified to something like this:
446
447 return $h->DBI::set_err($errcode, $errmsg) if ...;
448
449
450=item Other driver handle methods
451
452may follow here. In particular you should consider a I<data_sources>
453method, and a (possibly empty) I<disconnect_all> method. See L<DBI(3)>.
454
455
456=item The statement handle constructor
457
458There's nothing much new in the statement handle constructor.
459
460 package DBD::Driver::db; # ====== DATABASE ======
461
462 $DBD::Driver::db::imp_data_size = 0;
463
464 sub prepare {
465 my($dbh, $statement, @attribs)= @_;
466
467 # create a 'blank' sth
468 my $sth = DBI::_new_sth($dbh, {
469 'Statement' => $statement,
470 });
471
472 # Setup module specific data
473 $sth->STORE('driver_params', []);
474 $sth->STORE('NUM_OF_PARAMS', ($statement =~ tr/?//));
475
476 $sth;
477 }
478
479This is still the same: Check the arguments and call the super class
480constructor I<DBI::_new_sth>. Note the prefix I<driver_> in the
481attribute names: It is required that your private attributes
482are lowercased and use such a prefix. See the DBI manual.
483
484Note that we parse the statement here in order to setup the attribute
485I<NUM_OF_PARAMS>. We could as well do this in the I<execute> method
486below, the DBI specs explicitly allow to defer this. However, one
487could not call I<bind_param> in that case.
488
489
490=item Transaction handling
491
492Pure Perl drivers will rarely support transactions. Thus you're I<commit>
493and I<rollback> methods will typically be quite simple:
494
495 sub commit {
496 my($dbh) = @_;
497 if ($dbh->FETCH('Warn')) {
498 warn("Commit ineffective while AutoCommit is on");
499 }
500 1;
501 }
502
503 sub rollback {
504 my($dbh) = @_;
505 if ($dbh->FETCH('Warn')) {
506 warn("Rollback ineffective while AutoCommit is on");
507 }
508 0;
509 }
510
511
512=item The STORE and FETCH methods
513
514These methods (that we have already used, see above) are called for
515you, whenever the user does a
516
517 $dbh->{$attr} = $val;
518
519or, respectively,
520
521 $val = $dbh->{$attr};
522
523See L<perltie(1)> for details on tied hash refs to understand why these
524methods are required.
525
526The DBI will handle most attributes for you, in particular attributes
527like I<RaiseError> or I<PrintError>. All you have to do handle your
528driver's private attributes and any attributes, like AutoCommit, that
529the DBI can't handle for you. A good example might look like this:
530
531 sub STORE {
532 my($dbh, $attr, $val) = @_;
533 if ($attr eq 'AutoCommit') {
534 # AutoCommit is currently the only standard attribute we have
535 # to consider.
536 if (!$val) { die "Can't disable AutoCommit"; }
537 return 1;
538 }
539 if ($attr =~ /^driver_/) {
540 # Handle only our private attributes here
541 # Note that we could trigger arbitrary actions.
542 # Ideally we should catch unknown attributes.
543 $dbh->{$attr} = $val; # Yes, we are allowed to do this,
544 return 1; # but only for our private attributes
545 }
546 # Else pass up to DBI to handle for us
547 $dbh->SUPER::STORE($attr, $val);
548 }
549
550 sub FETCH {
551 my($dbh, $attr) = @_;
552 if ($attr eq 'AutoCommit') { return 1; }
553 if ($attr =~ /^driver_/) {
554 # Handle only our private attributes here
555 # Note that we could trigger arbitrary actions.
556 return $dbh->{$attr}; # Yes, we are allowed to do this,
557 # but only for our private attributes
558 }
559 # Else pass up to DBI to handle
560 $dbh->SUPER::FETCH($attr);
561 }
562
563The DBI will actually store and fetch driver-specific attributes (with all
564lowercase names) without warning or error, so there's actually no need to
565implement driver-specific any code in your FETCH and STORE methods unless
566you need extra logic/checks, beyond getting or setting the value.
567
568
569=item Other database handle methods
570
571may follow here. In particular you should consider a (possibly empty)
572I<disconnect> method, a I<quote> method (if DBI's default isn't good
573for you).
574
575
576=item The execute method
577
578This is perhaps the most difficult method because we have to consider
579parameter bindings here. We present a simplified implementation by
580using the I<driver_params> attribute from above:
581
582 package DBD::Driver::st;
583
584 $DBD::Driver::st::imp_data_size = 0;
585
586 sub bind_param {
587 my($sth, $pNum, $val, $attr) = @_;
588 my $type = (ref $attr) ? $attr->{TYPE} : $attr;
589 if ($type) {
590 my $dbh = $sth->{Database};
591 $val = $dbh->quote($sth, $type);
592 }
593 my $params = $sth->FETCH('driver_params');
594 $params->[$pNum-1] = $val;
595 1;
596 }
597
598 sub execute {
599 my($sth, @bind_values) = @_;
600 my $params = (@bind_values) ?
601 \@bind_values : $sth->FETCH('driver_params');
602 my $numParam = $sth->FETCH('NUM_OF_PARAMS');
603 if (@$params != $numParam) { ... }
604 my $statement = $sth->{'Statement'};
605 for (my $i = 0; $i < $numParam; $i++) {
606 $statement =~ s/?/$params->[$i]/e;
607 }
608 # Do anything ... we assume that an array ref of rows is
609 # created and store it:
610 $sth->{'driver_data'} = $data;
611 $sth->{'driver_rows'} = @$data; # number of rows
612 $sth->STORE('NUM_OF_FIELDS') = $numFields;
613 @$data || '0E0';
614 }
615
616Things you should note here: We setup the NUM_OF_FIELDS attribute
617here, because this is essential for I<bind_columns> to work. And
618we use attribute I<$sth->{'Statement'}> which we have created
619within I<prepare>. The attribute I<$sth->{'Database'}>, which is
620nothing else than the I<dbh>, was automatically created by DBI.
621
622Finally note that we return the string '0E0' instead of the number
6230, so that
624
625 if (!$sth->execute()) { die $sth->errstr }
626
627works.
628
629
630=item Fetching data
631
632We need not implement the methods I<fetchrow_array>, I<fetchall_arrayref>,
633... because these are already part of DBI. All we need is the method
634I<fetchrow_arrayref>:
635
636 sub fetchrow_arrayref {
637 my($sth) = @_;
638 my $data = $sth->FETCH('driver_data');
639 my $row = shift @$data;
640 if (!$row) { return undef; }
641 if ($sth->FETCH('ChopBlanks')) {
642 map { $_ =~ s/\s+$//; } @$row;
643 }
644 return $sth->_set_fbav($row);
645 }
646 *fetch = \&fetchrow_arrayref; # required alias for fetchrow_arrayref
647
648 sub rows { my($sth) = @_; $sth->FETCH('driver_rows'); }
649
650Note the use of the method I<_set_fbav>: This is required so that
651I<bind_col> and I<bind_columns> work.
652
653Fixing the broken implementation for correct handling of quoted
654question marks is left as an exercise to the reader. :-)
655
656
657=item Statement attributes
658
659The main difference between dbh and sth attributes is, that you
660should implement a lot of attributes here that are required by
661the DBI: For example I<NAME>, I<NULLABLE>, I<TYPE>, ...
662
663Besides that the STORE and FETCH methods are mainly the same
664as above for dbh's.
665
666
667=item Other statement methods
668
669A trivial C<finish> method to discard the stored data and do
670$sth->SUPER::finish;
671
672A C<table_info> method to return details of available tables.
673
674A C<type_info_all> method to return details of supported types.
675
676And perhaps some other methods that are not part of the DBI specs, in
677particular make metadata available. Considering Tim's last articles do
678yourself a favour and follow the ODBC driver.
679
680
681=back
682
683
684=head2 Tests
685
686The test process should conform as closely as possibly to the Perl
687standard test harness.
688
689In particular, most of the tests should be run in the t sub-directory,
690and should simply produce an 'ok' when run under 'make test'.
691For details on how this is done, see the Camel book and the section in
692Chapter 7, "The Standard Perl Library" on L<Test::Harness>.
693
694The tests may need to adapt to the type of database which is being
695used for testing, and to the privileges of the user testing the
696driver.
697
698The DBD::Informix test code has to adapt in a number of places to the
699type of database to which it is connected as different Informix
700databases have different capabilities.
701
702 [...More info TBS...]
703
704
705=head1 CREATING A NEW DRIVER USING C/XS
706
707Creating a new C/XS driver from scratch will always be a daunting task.
708You can and should greatly simplify your task by taking a good
709reference driver implementation and modifying that to match the
710database product for which you are writing a driver.
711
712The de facto reference driver has been the one for DBD::Oracle, written
713by Tim Bunce who is also the author of the DBI package. The DBD::Oracle
714module is a good example of a driver implemented around a C-level API.
715
716Nowadays it it seems better to base on DBD::ODBC, another driver
717maintained by Tim and Jeff Urlwin, because it offers a lot of metadata
718and seems to become the guideline for the future development. (Also as
719DBD::Oracle digs deeper into the Oracle 8 OCI interface it'll get even
720more hairly than it is now.)
721
722The DBD::Informix driver is a good reference for a driver implemented
723using 'embedded SQL'. DBD::Ingres may also be worth a look.
724
725 [...More info TBS...]
726
727=head2 REQUIREMENTS ON A DRIVER
728
729T.B.S.
730
731=head2 CODE TO BE WRITTEN
732
733A minimal driver will typically contain 9 files plus some tests.
734Assuming that your driver is called DBD::Driver, these files are:
735
736=over 4
737
738=item Driver.pm
739
740=item Driver.xs
741
742=item Driver.h
743
744=item dbdimp.h
745
746=item dbdimp.c
747
748=item Makefile.PL
749
750=item README
751
752=item MANIFEST
753
754=item lib/Bundle/DBD/Driver.pm
755
756=back
757
758
759=head2 Driver.pm
760
761The Driver.pm file is the same as for Pure Perl modules, see above.
762However, there are some subtile differences:
763
764=over 8
765
766=item *
767
768The variables $DBD::File::dr|db|st::imp_data_size are not defined
769here, but in the XS code, because they declare the size of certain
770C structures.
771
772=item *
773
774Some methods are typically moved to the XS code, in particular
775I<prepare>, I<execute>, I<disconnect>, I<disconnect_all> and the STORE
776and FETCH methods.
777
778=item *
779
780Other methods are still part of C<Driver.pm>, but have callbacks in
781the XS code.
782
783=back
784
785
786Now let's take a closer look at an excerpt of Oracle.pm (around version
7870.54, prior to Oracle 8 support) as an example. We ignore things that
788are already discussed for Pure Perl drivers or really Oracle specific.
789
790=over 2
791
792=item The database handle constructor
793
794 sub connect {
795 my($drh, $dbname, $user, $auth)= @_;
796
797 # Some database specific verifications, default settings
798 # and the like following here. This should only include
799 # syntax checks or similar stuff where it's legal to
800 # 'die' in case of errors.
801
802 # create a 'blank' dbh (call superclass constructor)
803 my $dbh = DBI::_new_dbh($drh, {
804 'Name' => $dbname,
805 'USER' => $user, 'CURRENT_USER' => $user,
806 });
807
808 # Call Oracle OCI orlon func in Oracle.xs file
809 # and populate internal handle data.
810 DBD::Oracle::db::_login($dbh, $dbname, $user, $auth)
811 or return undef;
812
813 $dbh;
814 }
815
816This is mostly the same as in the Pure Perl case, the exception being
817the use of the private I<_login> callback: This will really connect to
818the database. It is implemented in Driver.xst (you should not implement
819it) and calls I<dbd_db_login> from I<dbdimp.c>. See below for details.
820
821Since the DBI::_new_xxh methods can't fail in normal situations, we
822don't both checking $dbh before calling _login.
823
824=item The statement handle constructor
825
826There's nothing much new in the statement handle constructor. Like
827the I<connect> method it now has a C callback:
828
829 package DBD::Oracle::db; # ====== DATABASE ======
830 use strict;
831
832 sub prepare {
833 my($dbh, $statement, @attribs)= @_;
834
835 # create a 'blank' sth
836 my $sth = DBI::_new_sth($dbh, {
837 'Statement' => $statement,
838 });
839
840 # Call Oracle OCI oparse func in Oracle.xs file.
841 # (This will actually also call oopen for you.)
842 # and populate internal handle data.
843
844 DBD::Oracle::st::_prepare($sth, $statement, @attribs)
845 or return undef;
846
847 $sth;
848 }
849
850=back
851
852
853=head2 Driver.xs
854
855Driver.xs should look something like this:
856
857 #include "Driver.h"
858
859 DBISTATE_DECLARE;
860
861 INCLUDE: Driver.xsi
862
863 MODULE = DBD::Driver PACKAGE = DBD::Driver::db
864
865 /* Non-standard dbh XS methods following here, if any. */
866 /* Currently this includes things like _list_tables from */
867 /* DBD::mSQL and DBD::mysql. */
868
869 MODULE = DBD::Driver PACKAGE = DBD::Driver::st
870
871 /* Non-standard sth XS methods following here, if any. */
872 /* In particular this includes things like _list_fields from */
873 /* DBD::mSQL and DBD::mysql for accessing metadata. */
874
875Note especially the include of I<Driver.xsi> here: DBI inserts stub
876functions for almost all private methods here which will typically
877do much work for you. Wherever you really have to implement something,
878it will call a private function in I<dbdimp.c>: This is what you have
879to implement.
880
881
882=head2 Driver.h
883
884Driver.h should look like this:
885
886 #define NEED_DBIXS_VERSION 93
887
888 #include <DBIXS.h> /* installed by the DBI module */
889
890 #include "dbdimp.h"
891
892 #include <dbd_xsh.h> /* installed by the DBI module */
893
894
895=head2 Implementation header dbdimp.h
896
897This header file has two jobs:
898
899First it defines data structures for your private part of the handles.
900
901Second it defines macros that rename the generic names like
902I<dbd_db_login> to database specific names like I<ora_db_login>. This
903avoids name clashes and enables use of different drivers when you work
904with a statically linked perl.
905
906It also will have the important task of disabling XS methods that you
907don't want to implement.
908
909Finally, the macros will also be used to select alternate
910implementations of some functions. For example, the currently defined
911C<dbd_db_login> function is not passed the attribute hash. In future,
912if a dbd_db_login6 macro is defined (for a function with 6 arguments),
913it will be used instead with the attribute hash passed at the sixth
914argument.
915
916People liked to just pick Oracle's dbdimp.c and use the same names,
917structures and types. I strongly recommend against that: At first
918glance this saves time, but your implementation will be less readable.
919It was just a hell when I had to separate DBI specific parts, Oracle
920specific parts, mSQL specific parts and mysql specific parts in
921DBD::mysql's I<dbdimp.h> and I<dbdimp.c>. (DBD::mysql was a port of
922DBD::mSQL which was based on DBD::Oracle.) This part of the driver
923is I<your exclusive part>. Rewrite it from scratch, so it will be
924clean and short, in other words: A better piece of code. (Of course
925have an eye at other people's work.)
926
927 struct imp_drh_st {
928 dbih_drc_t com; /* MUST be first element in structure */
929
930 /* Insert your driver handle attributes here */
931 };
932
933 struct imp_dbh_st {
934 dbih_dbc_t com; /* MUST be first element in structure */
935
936 /* Insert your database handle attributes here */
937 };
938
939 struct imp_sth_st {
940 dbih_stc_t com; /* MUST be first element in structure */
941
942 /* Insert your statement handle attributes here */
943 };
944
945 /* Rename functions for avoiding name clashes; prototypes are */
946 /* in dbd_xst.h */
947 #define dbd_init ora_init
948 #define dbd_db_login ora_db_login
949 #define dbd_db_do ora_db_do
950 ... many more here ...
951
952This structures implement your private part of the handles. You I<have>
953to use the name I<imp_dbh_dr|db|st> and the first field I<must> be of
954type I<dbih_drc|dbc|stc_t>. You should never access this fields directly,
955except of using the I<DBIc_xxx> macros below.
956
957
958=head2 Implementation source dbdimp.c
959
960This is the main implementation file. I will drop a short note on any
961function here that's used in the I<Driver.xsi> template and thus B<has>
962to be implemented. Of course you can add private or better static
963functions here.
964
965Note that most people are still using Kernighan & Ritchie syntax here.
966I personally don't like this and especially in this documentation it
967cannot be of harm, so let's use ANSI. Finally Tim Bunce has announced
968interest in moving the DBI sources to ANSI as well.
969
970=over 2
971
972=item Initialization
973
974 #include "Driver.h"
975
976 DBISTATE_DECLARE;
977
978 void dbd_init(dbistate_t* dbistate) {
979 DBIS = dbistate; /* Initialize the DBI macros */
980 }
981
982dbd_init will be called when your driver is first loaded. These
983statements are needed for use of the DBI macros. They will include your
984private header file I<dbdimp.h> in turn.
985
986=item do_error
987
988You need a function to handle recording of errors. You can call it
989whatever you like, but we'll call it C<do_error> here.
990
991 void do_error(SV* h, int rc, char* what) {
992
993Note that I<h> is a generic handle, may it be a driver handle, a
994database or a statement handle.
995
996 D_imp_xxh(h);
997
998This macro will declare and initialize a variable I<imp_xxh> with
999a pointer to your private handle pointer. You may cast this to
1000to I<imp_drh_t>, I<imp_dbh_t> or I<imp_sth_t>.
1001
1002 SV *errstr = DBIc_ERRSTR(imp_xxh);
1003 sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */
1004 sv_setpv(errstr, what);
1005 DBIh_EVENT2(h, ERROR_event, DBIc_ERR(imp_xxh), errstr);
1006
1007Note the use of the macros DBIc_ERRSTR and DBIc_ERR for accessing the
1008handles error string and error code.
1009
1010The macro DBIh_EVENT2 will ensure that the attributes I<RaiseError>
1011and I<PrintError> work: That's all what you have to deal with them. :-)
1012
1013 if (dbis->debug >= 2)
1014 fprintf(DBILOGFP, "%s error %d recorded: %s\n",
1015 what, rc, SvPV(errstr,na));
1016
1017That's the first time we see how debug/trace logging works within a DBI
1018driver. Make use of this as often as you can!
1019
1020=item dbd_db_login
1021
1022 int dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname,
1023 char* user, char* auth) {
1024
1025This function will really connect to the database. The argument I<dbh>
1026is the database handle. I<imp_dbh> is the pointer to the handles private
1027data, as is I<imp_xxx> in I<do_error> above. The arguments I<dsn>,
1028I<user> and I<auth> correspond to the arguments of the driver handles
1029I<connect> method.
1030
1031You will quite often use database specific attributes here, that are
1032specified in the DSN. I recommend you parse the DSN within the
1033I<connect> method and pass them as handle attributes to I<dbd_db_login>.
1034Here's how you fetch them, as an example we use I<hostname> and I<port>
1035attributes:
1036
1037 /* This code assumes that the *second* attribute parameter to
1038 * DBI::_new_dbh was used to store an hash with login attributes
1039 */
1040 SV* imp_data = DBIc_IMP_DATA(dbh);
1041 HV* hv;
1042 SV** svp;
1043 char* hostname;
1044 char* port;
1045
1046 if (!SvTRUE(imp_data) || !SvROK(imp_data) ||
1047 SvTYPE(hv = (HV*) SvRV(imp_data)) != SVt_PVHV) {
1048 croak("Implementation dependent data invalid: Not a hash ref.\n");
1049 }
1050 if ((svp = hv_fetch(hv, "hostname", strlen("hostname"), FALSE)) &&
1051 SvTRUE(*svp)) {
1052 hostname = SvPV(*svp, na);
1053 } else {
1054 hostname = "localhost";
1055 }
1056 if ((svp = hv_fetch(hv, "port", strlen("port"), FALSE)) &&
1057 SvTRUE(*svp)) {
1058 port = SvPV(*svp, na); /* May be a service name */
1059 } else {
1060 port = DEFAULT_PORT;
1061 }
1062
1063Now you should really connect to the database. If you are successful
1064(or even if you fail, but you have allocated some resources), you should
1065use the following macros:
1066
1067 DBIc_IMPSET_on(imp_dbh);
1068
1069This indicates that the driver (implementor) has allocated resources in
1070the imp_dbh structure and that the implementors private dbd_db_destroy
1071function should be called when the handle is destroyed.
1072
1073 DBIc_ACTIVE_on(imp_dbh);
1074
1075This indicates that the handle has an active connection to the server
1076and that the dbd_db_disconnect function should be called before the
1077handle is destroyed.
1078
1079The dbd_db_login function should return TRUE for success, FALSE otherwise.
1080
1081
1082=item dbd_db_commit
1083
1084=item dbd_db_rollback
1085
1086 int dbd_db_commit( SV* dbh, imp_dbh_t* imp_dbh );
1087 int dbd_db_rollback( SV* dbh, imp_dbh_t* imp_dbh );
1088
1089These are used for commit and rollback. They should return TRUE for
1090success, FALSE for error.
1091
1092The arguments I<dbh> and I<imp_dbh> are like above, I will omit
1093describing them in what follows, as they appear always.
1094
1095
1096=item dbd_db_disconnect
1097
1098This is your private part of the I<disconnect> method. Any dbh with
1099the I<ACTIVE> flag on must be disconnected. (Note that you have to set
1100it in I<dbd_db_connect> above.)
1101
1102 int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh);
1103
1104The database handle will return TRUE for success, FALSE otherwise.
1105In any case it should do a
1106
1107 DBIc_ACTIVE_off(imp_dbh);
1108
1109before returning so DBI knows that I<dbd_db_disconnect> was executed.
1110
1111
1112=item dbd_db_discon_all
1113
1114 int dbd_discon_all (SV *drh, imp_drh_t *imp_drh) {
1115
1116This function may be called at shutdown time. It should make
1117best-efforts to disconnect all database handles - if possible. Some
1118databases don't support that, in which case you can do nothing
1119but return 'success'.
1120
1121You guess what the return codes are? (Hint: See the last functions
1122above ... :-)
1123
1124
1125=item dbd_db_destroy
1126
1127This is your private part of the database handle destructor. Any dbh with
1128the I<IMPSET> flag on must be destroyed, so that you can safely free
1129resources. (Note that you have to set it in I<dbd_db_connect> above.)
1130
1131 void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) {
1132 DBIc_IMPSET_off(imp_dbh);
1133 }
1134
1135The DBI Driver.xst code will have called dbd_db_disconnect for you,
1136if the handle is still 'active', before calling dbd_db_destroy.
1137
1138Before returning the function must switch IMPSET to off, so DBI knows
1139that the destructor was called.
1140
1141
1142=item dbd_db_STORE_attrib
1143
1144This function handles
1145
1146 $dbh->{$key} = $value;
1147
1148its prototype is
1149
1150 int dbd_db_STORE_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv,
1151 SV* valuesv);
1152
1153You do not handle all attributes, in contrary you should not handle
1154DBI attributes here: Leave this to DBI. (There's one exception,
1155I<AutoCommit>, which you should care about.)
1156
1157The return value is TRUE, if you have handled the attribute or FALSE
1158otherwise. If you are handling an attribute and something fails, you
1159should call I<do_error>, so DBI can raise exceptions, if desired.
1160If I<do_error> returns, however, you have a problem: The user will
1161never know about the error, because he typically will not check
1162C<$dbh-E<gt>errstr>.
1163
1164I cannot recommend a general way of going on, if I<do_error> returns,
1165but there are examples where even the DBI specification expects that
1166you croak(). (See the I<AutoCommit> method in L<DBI(3)>.)
1167
1168If you have to store attributes, you should either use your private
1169data structure imp_xxx, the handle hash (via (HV*)SvRV(dbh)), or use
1170the private imp_data.
1171
1172The first is best for internal C values like integers or pointers and
1173where speed is important within the driver. The handle hash is best for
1174values the user may want to get/set via driver-specific attributes.
1175The private imp_data is an additional SV attached to the handle. You
1176could think of it as an unnamed handle attribute. It's not normally used.
1177
1178
1179=item dbd_db_FETCH_attrib
1180
1181This is the counterpart of dbd_db_STORE_attrib, needed for
1182
1183 $value = $dbh->{$key};
1184
1185Its prototype is:
1186
1187 SV* dbd_db_FETCH_attrib(SV* dbh, imp_dbh_t* imp_dbh, SV* keysv) {
1188
1189Unlike all previous methods this returns an SV with the value. Note
1190that you should normally execute sv_2mortal, if you return a nonconstant
1191value. (Constant values are C<&sv_undef>, C<&sv_no> and C<&sv_yes>.)
1192
1193Note, that DBI implements a caching algorithm for attribute values.
1194If you think, that an attribute may be fetched, you store it in the
1195dbh itself:
1196
1197 if (cacheit) /* cache value for later DBI 'quick' fetch? */
1198 hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
1199
1200
1201=item dbd_st_prepare
1202
1203This is the private part of the I<prepare> method. Note that you
1204B<must not> really execute the statement here. You may, for example,
1205preparse and validate the statement or do similar things.
1206
1207 int dbd_st_prepare(SV* sth, imp_sth_t* imp_sth, char* statement,
1208 SV* attribs);
1209
1210A typical, simple possibility is just to store the statement in the
1211imp_data hash ref and use it in dbd_st_execute. If you can, you should
1212setup attributes like NUM_OF_FIELDS, NAME, ... here, but DBI
1213doesn't require that. However, if you do, document it.
1214
1215In any case you should set the IMPSET flag, as you did in
1216I<dbd_db_connect> above:
1217
1218 DBIc_IMPSET_on(imp_sth);
1219
1220
1221=item dbd_st_execute
1222
1223This is where a statement will really be executed.
1224
1225 int dbd_st_execute(SV* sth, imp_sth_t* imp_sth);
1226
1227Note, that you must be aware, that a statement may be executed repeatedly.
1228Also, you should not expect, that I<finish> will be called between
1229two executions.
1230
1231If your driver supports binding of parameters (he should!), but the
1232database doesn't, you must probably do it here. This can be done as
1233follows:
1234
1235 char* statement = dbd_st_get_statement(sth, imp_sth);
1236 /* Its your drivers task to implement this function. It */
1237 /* must restore the statement passed to preparse. */
1238 /* See use of imp_data above for an example of how to do */
1239 /* this. */
1240 int numParam = DBIc_NUM_PARAMS(imp_sth);
1241 int i;
1242
1243 for (i = 0; i < numParam; i++) {
1244 char* value = dbd_db_get_param(sth, imp_sth, i);
1245 /* Its your drivers task to implement dbd_db_get_param, */
1246 /* it must be setup as a counterpart of dbd_bind_ph. */
1247 /* Look for '?' and replace it with 'value'. Difficult */
1248 /* task, note that you may have question marks inside */
1249 /* quotes and the like ... :-( */
1250 /* See DBD::mysql for an example. (Don't look too deep into */
1251 /* the example, you will notice where I was lazy ...) */
1252 }
1253
1254The next thing is you really execute the statement. Note that you must
1255prepare the attributes NUM_OF_FIELDS, NAME, ... when the statement is
1256successfully executed if you have not already done so: They may be used even before a potential
1257I<fetchrow>. In particular you have to tell DBI the number of fields,
1258that the statement has, because it will be used by DBI internally.
1259Thus the function will typically ends with:
1260
1261 if (isSelectStatement) {
1262 DBIc_NUM_FIELDS(imp_sth) = numFields;
1263 DBIc_ACTIVE_on(imp_sth);
1264 }
1265
1266It is important that the ACTIVE flag only be set for select statements.
1267See I<dbd_st_preparse> and I<dbd_db_connect> above for more explanations.
1268
1269
1270=item dbd_st_fetch
1271
1272This function fetches a row of data. The row is stored in in an array,
1273of SV's that DBI prepares for you. This has two advantages: It is fast
1274(you even reuse the SV's, so they don't have to be created after the
1275first fetchrow) and it guarantees, that DBI handles I<bind_cols> for
1276you.
1277
1278What you do is the following:
1279
1280 AV* av;
1281 int numFields = DBIc_NUM_FIELDS(imp_sth); /* Correct, if NUM_FIELDS
1282 is constant for this statement. There are drivers where this is
1283 not the case! */
1284 int chopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
1285 int i;
1286
1287 if (!fetch_new_row_of_data(...)) {
1288 ... /* check for error or end-of-data */
1289 DBIc_ACTIVE_off(imp_sth); /* turn off Active flag automatically */
1290 return Nullav;
1291 }
1292 /* get the fbav (field buffer array value) for this row */
1293 /* it is very important to only call this after you know */
1294 /* that you have a row of data to return. */
1295 av = DBIS->get_fbav(imp_sth);
1296 for (i = 0; i < numFields; i++) {
1297 SV* sv = fetch_a_field(..., i);
1298 if (chopBlanks && SvOK(sv) && type_is_blank_padded(field_type[i])) {
1299 /* Remove white space from end (only) of sv */
1300 }
1301 sv_setsv(AvARRAY(av)[i], sv); /* Note: (re)use! */
1302 }
1303 return av;
1304
1305There's no need to use a fetch_a_field function returning an SV*.
1306It's more common to use your database API functions to fetch the
1307data as character strings and use code like this:
1308
1309 sv_setpvn(AvARRAY(av)[i], char_ptr, char_count);
1310
1311NULL values must be returned as undef. You can use code like this:
1312
1313 SvOK_off(AvARRAY(av)[i]);
1314
1315The function returns the AV prepared by DBI for success or C<Nullav>
1316otherwise.
1317
1318
1319=item dbd_st_finish
1320
1321This function can be called if the user wishes to indicate that no
1322more rows will be fetched even if the server has more rows to offer.
1323See the DBI docs for more background details.
1324
1325All it I<needs> to do is turn off the Active flag for the sth.
1326It will only be called by Driver.xst code, if the driver has set
1327ACTIVE to on for the sth.
1328
1329Minimal example (the DBI default method just does this):
1330
1331 int dbd_st_finish(SV* sth, imp_sth_t* imp_sth) {
1332 DBIc_ACTIVE_off(imp_sth);
1333 return 1;
1334 }
1335
1336The function returns TRUE for success, FALSE otherwise.
1337
1338
1339=item dbd_st_destroy
1340
1341This function is the private part of the statement handle destructor.
1342
1343 void dbd_st_destroy(SV* sth, imp_sth_t* imp_sth);
1344 ... /* any clean-up that's needed */
1345 DBIc_IMPSET_off(imp_sth); /* let DBI know we've done it */
1346 }
1347
1348The DBI Driver.xst code will call dbd_st_finish for you, if the sth has
1349the ACTIVE flag set, before calling dbd_st_destroy.
1350
1351=item dbd_st_STORE_attrib
1352
1353=item dbd_st_FETCH_attrib
1354
1355These functions correspond to dbd_db_STORE|FETCH attrib above, except
1356that they are for statement handles. See above.
1357
1358 int dbd_st_STORE_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv,
1359 SV* valuesv);
1360 SV* dbd_st_FETCH_attrib(SV* sth, imp_sth_t* imp_sth, SV* keysv);
1361
1362
1363=item dbd_bind_ph
1364
1365This function is internally used by the I<bind_param> method, the
1366I<bind_param_inout> method and by the DBI Driver.xst code if C<execute>
1367is called with any bind parameters.
1368
1369 int dbd_bind_ph (SV *sth, imp_sth_t *imp_sth, SV *param,
1370 SV *value, IV sql_type, SV *attribs,
1371 int is_inout, IV maxlen);
1372
1373The I<param> argument holds an IV with the parameter number (1, 2, ...).
1374The I<value> argument is the parameter value and I<sql_type> is its type.
1375
1376If your driver does not support bind_param_inout then you should
1377ignore I<maxlen> and croak if I<is_inout> is TRUE.
1378
1379If your driver I<does> support bind_param_inout then you should
1380note that I<value> is the SV I<after> dereferencing the reference
1381passed to bind_param_inout.
1382
1383In drivers of simple databases the function will, for example, store
1384the value in a parameter array and use it later in I<dbd_st_execute>.
1385See the I<DBD::mysql> driver for an example.
1386
1387
1388=back
1389
1390=head2 Implementing bind_param_inout support
1391
1392To provide support for parameters bound by reference rather than by
1393value, the driver must do a number of things. First, and most
1394importantly, it must note the references and stash them in its own
1395driver structure. Secondly, when a value is bound to a column, the
1396driver must discard any previous reference bound to the column. On
1397each execute, the driver must evaluate the references and internally
1398bind the values resulting from the references. This is only applicable
1399if the user writes:
1400
1401 $sth->execute;
1402
1403If the user writes:
1404
1405 $sth->execute(@values);
1406
1407then DBI automatically calls the binding code for each element of
1408@values. These calls are indistinguishable from explicit user calls to
1409bind_param.
1410
1411
1412=head2 Makefile.PL
1413
1414This is exactly as in the Pure Perl case. To be honest, the above
1415Makefile.PL contains some things that are superfluous for Pure Perl
1416drivers. :-)
1417
1418
1419=head1 METHODS WHICH DO NOT NEED TO BE WRITTEN
1420
1421The DBI code implements the majority of the methods which are
1422accessed using the notation DBI->function(), the only exceptions being
1423DBI->connect() and DBI->data_sources() which require support from the
1424driver.
1425
1426The DBI code implements the following documented driver, database and
1427statement functions which do not need to be written by the DBD driver
1428writer.
1429
1430=over 4
1431
1432=item $dbh->do()
1433
1434The default implementation of this function prepares, executes and
1435destroys the statement. This can be replaced if there is a better
1436way to implement this, such as EXECUTE IMMEDIATE which can
1437sometimes be used if there are no parameters.
1438
1439=item $h->errstr()
1440
1441=item $h->err()
1442
1443=item $h->state()
1444
1445=item $h->trace()
1446
1447The DBD driver does not need to worry about these routines at all.
1448
1449=item $h->{ChopBlanks}
1450
1451This attribute needs to be honured during fetch operations, but does
1452not need to be handled by the attribute handling code.
1453
1454=item $h->{RaiseError}
1455
1456The DBD driver does not need to worry about this attribute at all.
1457
1458=item $h->{PrintError}
1459
1460The DBD driver does not need to worry about this attribute at all.
1461
1462=item $sth->bind_col()
1463
1464Assuming the driver uses the DBIS->get_fbav() function (C drivers,
1465see below), or the $sth->_set_fbav($data) method (Perl drivers)
1466the driver does not need to do anything about this routine.
1467
1468=item $sth->bind_columns()
1469
1470Regardless of whether the driver uses DBIS->get_fbav(), the driver
1471does not need to do anything about this routine as it simply
1472iteratively calls $sth->bind_col().
1473
1474=back
1475
1476The DBI code implements a default implementation of the following
1477functions which do not need to be written by the DBD driver writer
1478unless the default implementation is incorrect for the Driver.
1479
1480=over 4
1481
1482=item $dbh->quote()
1483
1484This should only be written if the database does not accept the ANSI
1485SQL standard for quoting strings, with the string enclosed in single
1486quotes and any embedded single quotes replaced by two consecutive
1487single quotes.
1488
1489For the two argument form of quote, you need to implement the
1490C<type_info> method to provide the information that quote needs.
1491
1492=item $dbh->ping()
1493
1494This should be implemented as a simple efficient way to determine
1495whether the connection to the database is still alive. Typically
1496code like this:
1497
1498 sub ping {
1499 my $dbh = shift;
1500 $sth = $dbh->prepare_cached(q{
1501 select * from A_TABLE_NAME where 1=0
1502 }) or return 0;
1503 $sth->execute or return 0;
1504 $sth->finish;
1505 return 1;
1506 }
1507
1508where A_TABLE_NAME is the name of a table that always exists (such as a
1509database system catalogue).
1510
1511=back
1512
1513
1514=head1 WRITING AN EMULATION LAYER FOR AN OLD PERL INTERFACE
1515
1516Study Oraperl.pm (supplied with DBD::Oracle) and Ingperl.pm (supplied
1517with DBD::Ingres) and the corresponding dbdimp.c files for ideas.
1518
1519Note that the emulation code sets $dbh->{CompatMode} = 1; for each
1520connection so that the internals of the driver can implement behaviour
1521compatible with the old interface when dealing with those handles.
1522
1523=head2 Setting emulation perl variables
1524
1525For example, ingperl has a $sql_rowcount variable. Rather than try
1526to manually update this in Ingperl.pm it can be done faster in C code.
1527In dbd_init():
1528
1529 sql_rowcount = perl_get_sv("Ingperl::sql_rowcount", GV_ADDMULTI);
1530
1531In the relevant places do:
1532
1533 if (DBIc_COMPAT(imp_sth)) /* only do this for compatibility mode handles */
1534 sv_setiv(sql_rowcount, the_row_count);
1535
1536
1537=head1 OTHER MISCELLANEOUS INFORMATION
1538
1539=head2 The imp_xyz_t types
1540
1541Any handle has a corresponding C structure filled with private data.
1542Some of this data is reserved for use by DBI (except for using the
1543DBIc macros below), some is for you. See the description of the
1544I<dbdimp.h> file above for examples. The most functions in dbdimp.c
1545are passed both the handle C<xyz> and a pointer to C<imp_xyz>. In
1546rare cases, however, you may use the following macros:
1547
1548=over 2
1549
1550=item D_imp_dbh(dbh)
1551
1552Given a function argument I<dbh>, declare a variable I<imp_dbh> and
1553initialize it with a pointer to the handles private data. Note: This
1554must be a part of the function header, because it declares a variable.
1555
1556=item D_imp_sth(sth)
1557
1558Likewise for statement handles.
1559
1560=item D_imp_xxx(h)
1561
1562Given any handle, declare a variable I<imp_xxx> and initialize it
1563with a pointer to the handles private data. It is safe, for example,
1564to cast I<imp_xxx> to C<imp_dbh_t*>, if DBIc_TYPE(imp_xxx) == DBIt_DB.
1565(You can also call sv_derived_from(h, "DBI::db"), but that's much
1566slower.)
1567
1568=item D_imp_sth_from_dbh
1569
1570Given a imp_sth, declare a variable I<imp_dbh> and initialize it with a
1571pointer to the parent database handles implementors structure.
1572
1573=back
1574
1575
1576=head2 Using DBIc_IMPSET_on
1577
1578The driver code which initializes a handle should use DBIc_IMPSET_on()
1579as soon as its state is such that the cleanup code must be called.
1580When this happens is determined by your driver code.
1581
1582Failure to call this can lead to corruption of data structures.
1583For example, DBD::Informix maintains a linked list of database handles
1584in the driver, and within each handle, a linked list of statements.
1585Once a statement is added to the linked list, it is crucial that it is
1586cleaned up (removed from the list).
1587When DBIc_IMPSET_on() was being called too late, it was able to cause
1588all sorts of problems.
1589
1590
1591=head2 Using DBIc_is(), DBIc_has(), DBIc_on() and DBIc_off()
1592
1593Once upon a long time ago, the only way of handling the internal DBI
1594boolean flags/attributes was through macros such as:
1595
1596 DBIc_WARN DBIc_WARN_on DBIc_WARN_off
1597 DBIc_COMPAT DBIc_COMPAT_on DBIc_COMPAT_off
1598
1599Each of these took an imp_xxh pointer as an argument.
1600
1601Since then, new attributes have been added such as ChopBlanks,
1602RaiseError and PrintError, and these do not have the full set of
1603macros.
1604The approved method for handling these is now the four macros:
1605
1606 DBIc_is(imp, flag)
1607 DBIc_has(imp, flag) an alias for DBIc_is
1608 DBIc_on(imp, flag)
1609 DBIc_off(imp, flag)
1610
1611Consequently, the DBIc_XXXXX family of macros is now mostly deprecated
1612and new drivers should avoid using them, even though the older drivers
1613will probably continue to do so for quite a while yet. However...
1614
1615There is an I<important exception> to that. The ACTIVE and IMPSET
1616flags should be set via the DBIc_ACTIVE_on and DBIc_IMPSET_on macros,
1617and unset via the DBIc_ACTIVE_off and DBIc_IMPSET_off macros.
1618
1619
1620=head2 Using DBIS->get_fbav()
1621
1622The $sth->bind_col() and $sth->bind_columns() documented in the DBI
1623specification do not have to be implemented by the driver writer
1624becuase DBI takes care of the details for you.
1625However, the key to ensuring that bound columns work is to call the
1626function DBIS->get_fbav() in the code which fetches a row of data.
1627This returns an AV, and each element of the AV contains the SV which
1628should be set to contain the returned data.
1629
1630The above is for C drivers only. The Perl equivalent is the
1631$sth->_set_fbav($data) method, as described in the part on Pure
1632Perl drivers.
1633
1634
1635=head1 SUBCLASSING DBI DRIVERS
1636
1637This is definitely an open subject. It can be done, as demonstrated by
1638the I<DBD::File> driver, but it is not as simple as one might think.
1639
1640(Note that this topic is different from subclassing the DBI. For an
1641example of that, see the t/subclass.t file supplied with the DBI.)
1642
1643The main problem is that the dbh's and sth's that your I<connect> and
1644I<prepare> methods return are not instances of your I<DBD::Driver::db>
1645or I<DBD::Driver::st> packages, they are not even derived from it.
1646Instead they are instances of the I<DBI::db> or I<DBI::st> classes or
1647a derived subclass. Thus, if you write a method I<mymethod> and do a
1648
1649 $dbh->mymethod()
1650
1651then the autoloader will search for that method in the package I<DBI::db>.
1652Of course you can instead to a
1653
1654 $dbh->func('mymethod')
1655
1656and that will indeed work, even if I<mymethod> is inherited, but not
1657without additional work. Setting C<@ISA> is not sufficient.
1658
1659
1660=head2 Overwriting methods
1661
1662The first problem is, that the I<connect> method has no idea of
1663subclasses. For example, you cannot implement base class and subclass
1664in the same file: The I<install_driver> method wants to do a
1665
1666 require DBD::Driver;
1667
1668In particular, your subclass B<has> to be a separate driver, from
1669the view of DBI, and you cannot share driver handles.
1670
1671Of course that's not much of a problem. You should even be able
1672to inherit the base classes I<connect> method. But you cannot
1673simply overwrite the method, unless you do something like this,
1674quoted from I<DBD::CSV>:
1675
1676 sub connect ($$;$$$) {
1677 my($drh, $dbname, $user, $auth, $attr) = @_;
1678
1679 my $this = $drh->DBD::File::dr::connect($dbname, $user, $auth, $attr);
1680 if (!exists($this->{csv_tables})) {
1681 $this->{csv_tables} = {};
1682 }
1683
1684 $this;
1685 }
1686
1687Note that we cannot do a
1688
1689 $srh->SUPER::connect($dbname, $user, $auth, $attr);
1690
1691as we would usually do in a an OO environment, because $drh is an instance
1692of I<DBI::dr>. And note, that the I<connect> method of I<DBD::File> is
1693able to handle subclass attributes. See the description of Pure Perl
1694drivers above.
1695
1696It is essential that you always call superclass method in the above
1697manner. However, that should do.
1698
1699
1700=head2 Attribute handling
1701
1702Fortunately the DBI specs allow a simple, but still performant way of
1703handling attributes. The idea is based on the convention that any
1704driver uses a prefix I<driver_> for its private methods. Thus it's
1705always clear whether to pass attributes to the super class or not.
1706For example, consider this STORE method from the I<DBD::CSV> class:
1707
1708 sub STORE {
1709 my($dbh, $attr, $val) = @_;
1710 if ($attr !~ /^driver_/) {
1711 return $dbh->DBD::File::db::STORE($attr, $val);
1712 }
1713 if ($attr eq 'driver_foo') {
1714 ...
1715 }
1716
1717
1718=head1 ACKNOWLEDGEMENTS
1719
1720Tim Bunce - for writing DBI and managing the DBI specification and the
1721DBD::Oracle driver.
1722
1723
1724=head1 AUTHORS
1725
1726Jonathan Leffler <jleffler@informix.com>,
1727Jochen Wiedmann <joe@ispsoft.de>,
1728and Tim Bunce.
1729
1730=cut
1731
1732
1733package DBI::DBD;
1734
1735use Exporter ();
1736use Config;
1737use Carp;
1738use strict;
1739use vars qw(
1740 @ISA @EXPORT $VERSION
1741 $is_dbi
1742);
1743
1744BEGIN { if ($^O eq 'VMS') {
1745 require vmsish;
1746 import vmsish;
1747 require VMS::Filespec;
1748 import VMS::Filespec;
1749}}
1750
1751@ISA = qw(Exporter);
1752
1753$VERSION = substr(q$Revision: 10.9 $, 10);
1754
1755@EXPORT = qw(
1756 dbd_dbi_dir dbd_dbi_arch_dir
1757 dbd_edit_mm_attribs dbd_postamble
1758);
1759
1760BEGIN {
1761 $is_dbi = (-r 'DBI.pm' && -r 'DBI.xs' && -r 'DBIXS.h');
1762 require DBI unless $is_dbi;
1763}
1764
1765
1766sub dbd_edit_mm_attribs {
1767 my %a = @_;
1768
1769 return %a;
1770}
1771
1772
1773sub dbd_dbi_dir {
1774 return '.' if $is_dbi;
1775 my $dbidir = $INC{'DBI.pm'} || die "DBI.pm not in %INC!";
1776 $dbidir =~ s:/DBI\.pm$::;
1777 return $dbidir;
1778}
1779
1780sub dbd_dbi_arch_dir {
1781 if ($is_dbi) {
1782 return '$(INST_ARCHAUTODIR)'
1783 }
1784 my $dbidir = dbd_dbi_dir();
1785 my @try = map { "$_/auto/DBI" } @INC;
1786 my @xst = grep { -f "$_/Driver.xst" } @try;
1787 Carp::croak("Unable to locate Driver.xst in @try") unless @xst;
1788 Carp::carp( "Multiple copies of Driver.xst found in: @xst") if @xst > 1;
1789 print "Using DBI $DBI::VERSION installed in $xst[0]\n";
1790 return $xst[0];
1791}
1792
1793
1794sub dbd_postamble {
1795 my $dbidir = dbd_dbi_dir();
1796 my $xstdir = dbd_dbi_arch_dir();
1797 my $xstfile= '$(DBI_INSTARCH_DIR)/Driver.xst';
1798 if ($^O eq 'VMS') {
1799 $dbidir = vmsify($dbidir.'/');
1800 $xstdir = vmsify($xstdir.'/') unless $is_dbi;
1801 $xstfile= '$(DBI_INSTARCH_DIR)Driver.xst';
1802 }
1803
1804 # we must be careful of quotes, expecially for Win32 here.
1805 '
1806# This section was generated by DBI::DBD::dbd_postamble()
1807DBI_INST_DIR='.$dbidir.'
1808DBI_INSTARCH_DIR='.$xstdir.'
1809DBI_DRIVER_XST='.$xstfile.'
1810
1811# The main dependancy (technically correct but probably not used)
1812$(BASEEXT).c: $(BASEEXT).xsi
1813
1814# This dependancy is needed since MakeMaker uses the .xs.o rule
1815$(BASEEXT)$(OBJ_EXT): $(BASEEXT).xsi
1816
1817$(BASEEXT).xsi: $(DBI_DRIVER_XST)
1818 $(PERL) -p -e "s/~DRIVER~/$(BASEEXT)/g" < $(DBI_DRIVER_XST) > $(BASEEXT).xsi
1819';
1820}
1821
18221;
1823
1824__END__