File Coverage

blib/lib/Class/DBI/ViewLoader.pm
Criterion Covered Total %
statement 253 273 92.6
branch 78 90 86.6
condition 5 6 83.3
subroutine 63 68 92.6
pod 30 30 100.0
total 429 467 91.8


line stmt bran cond sub pod time code
1             package Class::DBI::ViewLoader;
2              
3 7     7   431815 use strict;
  7         15  
  7         502  
4 7     7   42 use warnings;
  7         12  
  7         557  
5              
6             our $VERSION = '0.05';
7              
8             =head1 NAME
9              
10             Class::DBI::ViewLoader - Load views from existing databases as Class::DBI
11             classes
12              
13             =head1 SYNOPSIS
14              
15             use Class::DBI::ViewLoader;
16              
17             # set up loader object
18             $loader = new Class::DBI::ViewLoader (
19             dsn => 'dbi:Pg:dbname=mydb',
20             username => 'me',
21             password => 'mypasswd',
22             options => {
23             RaiseError => 1,
24             AutoCommit => 1
25             },
26             namespace => 'MyClass::View',
27             exclude => qr(^te(?:st|mp)_)i,
28             include => qr(_foo$),
29             import_classes => [qw(
30             Class::DBI::Plugin::RetrieveAll
31             Class::DBI::AbstractSearch
32             )];
33             base_classes => [qw(
34             MyBase
35             )],
36             accessor_prefix => 'get_',
37             mutator_prefix => 'set_',
38             );
39              
40             # create classes
41             @classes = $loader->load_views;
42              
43             # retrieve all rows from view live_foo
44             MyClass::View::LiveFoo->retrieve_all()
45              
46             # Get the class name from the view name
47             $class = $loader->view_to_class('live_foo');
48              
49             # Works for views that weren't loaded too
50             $unloaded_class = $loader->view_to_class('test_foo');
51              
52             =head1 DESCRIPTION
53              
54             This class loads views from databases as L classes. It follows
55             roughly the same interface employed by L.
56              
57             This class behaves as a base class for the database-dependent driver classes,
58             which are loaded by L. Objects are reblessed into the
59             relevant subclass as soon as the driver is discovered, see set_dsn(). Driver
60             classes should always be named Class::DBI::ViewLoader::Edriver_nameE.
61              
62             =cut
63              
64             use Module::Pluggable (
65 7         56 search_path => __PACKAGE__,
66             require => 1,
67             inner => 0
68 7     7   7484 );
  7         86484  
69              
70 7     7   8206 use Class::DBI;
  7         440829  
  7         87  
71 7     7   318 use DBI 1.43;
  7         231  
  7         380  
72              
73 7     7   7268 use UNIVERSAL qw( can isa );
  7         101  
  7         41  
74              
75 7     7   4129 use Carp qw( carp croak confess );
  7         16  
  7         31328  
76              
77             our %handlers = reverse map { /(.*::(.*))/ } __PACKAGE__->plugins();
78              
79             # Keep a record of all the classes we've created so we can avoid creating the
80             # same one twice
81             our %class_cache;
82              
83             =head1 CONSTRUCTOR
84              
85             =head2 new
86              
87             $obj = $class->new(%args)
88              
89             Instantiates a new object. The values of %args are passed to the relevant set_*
90             accessors, detailed below. The following 2 statements should be equivalent:
91              
92             new Class::DBI::ViewLoader ( dsn => $dsn, username => $user );
93              
94             new Class::DBI::ViewLoader->set_dsn($dsn)->set_username($user);
95              
96             For compatibilty with L, the following aliases are provided
97             for use in the arguments to new() only.
98              
99             =over 4
100              
101             =item * user -> username
102              
103             =item * additional_classes -> import_classes
104              
105             =item * additional_base_classes -> base_classes
106              
107             =item * constraint -> include
108              
109             =back
110              
111             the debug and relationships options are not supported but are silently ignored.
112              
113             So
114              
115             new Class::DBI::ViewLoader user => 'me', constraint => '^foo', debug => 1;
116              
117             Is equivalent to:
118              
119             new Class::DBI::ViewLoader username => 'me', include => '^foo';
120              
121              
122             Unrecognised options will cause a fatal error to be raised, see DIAGNOSTICS.
123              
124             =cut
125              
126             # Class::DBI::Loader compatibility
127             my %compat = (
128             user => 'username',
129             additional_classes => 'import_classes',
130             additional_base_classes => 'base_classes',
131             constraint => 'include',
132              
133             # False values to cause silent skipping
134             debug => '',
135             relationships => '',
136             );
137              
138             sub new {
139 18     18 1 53031 my($class, %args) = @_;
140              
141 18         68 my $self = bless {}, $class;
142              
143             # Do dsn first, as we may be reblessed
144 18 100       82 if ($args{'dsn'}) {
145 8         38 $self->set_dsn(delete $args{'dsn'});
146             }
147              
148 15         54 $self->_compat(\%args);
149              
150 15         41 for my $arg (keys %args) {
151 17 100       146 if (my $setter = $self->can("set_$arg")) {
152 16         58 &$setter($self, delete $args{$arg});
153             }
154             }
155              
156 15 100       55 if (%args) {
157             # All supported arguments should have been deleted
158 1         9 my $extra = join(', ', map {"'$_'"} sort keys %args);
  1         5  
159 1         220 croak "Unrecognised arguments in new: $extra";
160             }
161              
162 14         66 return $self;
163             }
164              
165             sub _compat {
166 21     21   40 my ($self, $args) = @_;
167              
168 21         66 for my $arg (keys %$args) {
169 24 50       91 if (defined $compat{$arg}) {
170 0         0 my $value = delete $args->{$arg};
171              
172             # silently skip unsupported Class::DBI::Loader args
173 0 0       0 $arg = $compat{$arg} or next;
174 0         0 $args->{$arg} = $value;
175             }
176             }
177              
178 21         48 return $self;
179             }
180              
181             =head1 ACCESSORS
182              
183             =head2 set_dsn
184              
185             $obj = $obj->set_dsn($dsn_string)
186              
187             Sets the datasource for the object. This should be in the form understood by
188             L e.g. "dbi:Pg:dbname=mydb"
189              
190             Calling this method will rebless the object into a handler class for the given
191             driver. If no such handler is installed, "No handler for driver" will be raised
192             via croak(). See DIAGNOSTICS for other fatal errors raised by this method.
193              
194             =cut
195              
196             sub set_dsn {
197 14     14 1 2012 my($self, $dsn) = @_;
198              
199 14 100       153 croak "No dsn" unless $dsn;
200              
201 13 100       71 my $driver = (DBI->parse_dsn($dsn))[1]
202             or croak "Invalid dsn '$dsn'";
203              
204 12         273 $self->_load_driver($driver)->{_dsn} = $dsn;
205              
206 10         36 return $self;
207             }
208              
209             # rebless into driver class
210             sub _load_driver {
211 16     16   33 my ($self, $driver) = @_;
212              
213 16         44 my $handler = $handlers{$driver};
214              
215 16 100       38 if ($handler) {
216 15 100       122 if (isa($handler, __PACKAGE__)) {
217             # rebless into handler class
218 14         43 bless $self, $handler;
219             }
220             else {
221 1         142 confess "$handler is not a ".__PACKAGE__." subclass";
222             }
223             }
224             else {
225 1         137 croak "No handler for driver '$driver'";
226             }
227              
228 14         70 return $self;
229             }
230              
231             =head2 get_dsn
232              
233             $dsn = $obj->get_dsn
234              
235             Returns the dsn string, as passed in by set_dsn.
236              
237             =cut
238              
239 0     0 1 0 sub get_dsn { $_[0]->{_dsn} }
240              
241             =head2 set_username
242              
243             $obj = $obj->set_username($username)
244              
245             Sets the username to use when connecting to the database.
246              
247             =cut
248              
249             sub set_username {
250 3     3 1 2240 my($self, $user) = @_;
251              
252             # force stringification
253 3 100       14 $user = "$user" if defined $user;
254              
255 3         9 $self->{_username} = $user;
256              
257 3         8 return $self;
258             }
259              
260             =head2 get_username
261              
262             $username = $obj->get_username
263              
264             Returns the username.
265              
266             =cut
267              
268 1     1 1 547 sub get_username { $_[0]->{_username} }
269              
270             =head2 set_password
271              
272             $obj = $obj->set_password
273              
274             Sets the password to use when connecting to the database.
275              
276             =cut
277              
278             sub set_password {
279 3     3 1 479 my($self, $pass) = @_;
280              
281             # force stringification
282 3 100       12 $pass = "$pass" if defined $pass;
283              
284 3         7 $self->{_password} = $pass;
285              
286 3         9 return $self;
287             }
288              
289             =head2 get_password
290              
291             $password = $obj->get_password
292              
293             Returns the password
294              
295             =cut
296              
297 1     1 1 519 sub get_password { $_[0]->{_password} }
298              
299             =head2 set_options
300              
301             $obj = $obj->set_dbi_options(%opts)
302              
303             Accepts a hash or a hash reference.
304              
305             Sets the additional configuration options to pass to L.
306              
307             The hash will be copied internally, to guard against any accidental
308             modification after assignment.
309              
310             Options specified affect how the database that is used by the loader is built.
311             This is not always the same handle that is used by generated classes.
312              
313             =cut
314              
315             sub set_options {
316 0     0 1 0 my $self = shift;
317 0 0       0 my $opts = { ref $_[0] ? %{ $_[0] } : @_ };
  0         0  
318              
319 0         0 $self->{_dbi_options} = $opts;
320              
321 0         0 return $self;
322             }
323              
324             =head2 get_options
325              
326             \%opts = $obj->get_dbi_options
327              
328             Returns the DBI options hash. The return value should always be a hash
329             reference, even if there are no dbi options set.
330              
331             The reference returned by this function is live, so modification of it directly
332             affects the object.
333              
334             =cut
335              
336             sub get_options {
337 0     0 1 0 my $self = shift;
338              
339             # set up an empty options hash if there is none available.
340 0 0       0 $self->set_options unless $self->{_dbi_options};
341              
342 0         0 return $self->{_dbi_options};
343             }
344              
345             # Return this object's complete arguments to send to DBI.
346             sub _get_dbi_args {
347 14     14   19 my $self = shift;
348              
349             # breaking encapsulation to use hashslice:
350 14         134 return @$self{qw( _dsn _username _password _dbi_options )};
351             }
352              
353             # Return a new or existing DBI handle
354             # Drivers should use this method to access the database
355             sub _get_dbi_handle {
356 3     3   539 my $self = shift;
357              
358 3 100       16 return $self->{_dbh} if $self->{_dbh};
359              
360 2 100       7 my $dbh = DBI->connect( $self->_get_dbi_args )
361             or croak "Couldn't connect to database, $DBI::errstr";
362              
363 1         521 $self->_set_dbi_handle($dbh);
364              
365 1         3 return $dbh;
366             }
367              
368             # set the DBI handle. Might one day be called directly..
369             sub _set_dbi_handle {
370 5     5   11 my $self = shift;
371 5         10 my $dbh = shift;
372              
373 5         20 $self->_clear_dbi_handle;
374 5         17 $self->{_dbh} = $dbh;
375              
376 5         22 return $self;
377             }
378              
379             # disconnect current DBI handle, if any
380             sub _clear_dbi_handle {
381 23     23   31 my $self = shift;
382              
383 23 100       66 return $self if $self->_keepalive;
384              
385 19 100       62 if (defined $self->{_dbh}) {
386 1         9 delete($self->{_dbh})->disconnect;
387             }
388              
389 19         322 return $self;
390             }
391              
392             sub DESTROY {
393 18     18   5143 my $self = shift;
394              
395 18         60 $self->_clear_dbi_handle;
396             }
397              
398             # switch to disable _clear_dbi_handle
399             sub _set_keepalive {
400 4     4   6 my $self = shift;
401 4         9 $self->{__keepalive} = shift;
402 4         21 return $self;
403             }
404              
405             # check status of switch
406             sub _keepalive {
407 23     23   32 my $self = shift;
408 23         124 return $self->{__keepalive};
409             }
410              
411             =head2 set_namespace
412              
413             $obj = $obj->set_namespace($namespace)
414              
415             Sets the namespace to load views into. This should be a valid perl package name,
416             with or without a trailing '::'.
417              
418             =cut
419              
420             sub set_namespace {
421 12     12 1 27 my($self, $namespace) = @_;
422              
423 12         32 $namespace =~ s/::$//;
424              
425 12         36 $self->{_namespace} = $namespace;
426              
427 12         63 return $self;
428             }
429              
430             =head2 get_namespace
431              
432             $namespace = $obj->get_namespace
433              
434             Returns the target namespace. If not set, returns an empty list.
435              
436             =cut
437              
438             sub get_namespace {
439 26     26 1 40 my $self = shift;
440 26         50 my $out = $self->{_namespace};
441              
442 26 100 66     117 if (defined $out and length $out) {
443 24         97 return $out;
444             }
445             else {
446 2         7 return;
447             }
448             }
449              
450             =head2 set_include
451              
452             $obj = $obj->set_include($regexp)
453              
454             Sets a regexp that matches the views to load. Only views that match this expression will be loaded, unless they also match the exclude expression.
455              
456             Accepts strings or Regexps, croaks if any other reference is passed.
457              
458             The value is stored as a Regexp, even if a string was passed in.
459              
460             =cut
461              
462             sub set_include {
463 4     4 1 6193 my($self, $include) = @_;
464              
465 4         20 $self->{_include} = $self->_compile_regex($include);
466              
467 3         11 return $self;
468             }
469              
470             =head2 get_include
471              
472             $regexp = $obj->get_include
473              
474             Returns the include regular expression.
475              
476             Note that this may not be identical to what was passed in.
477              
478             =cut
479              
480 14     14 1 37 sub get_include { $_[0]->{_include} }
481              
482             =head2 set_exclude
483              
484             $obj = $obj->set_exclude($regexp)
485              
486             Sets a regexp to use to rule out views. Any view that matches this regex will
487             not be loaded by load_views(), even if it is explicitly included by the include
488             rule.
489              
490             Accepts strings or Regexps, croaks if any other reference is passed.
491              
492             The value is stored as a Regexp, even if a string was passed in.
493              
494             =cut
495              
496             sub set_exclude {
497 2     2 1 1063 my($self, $exclude) = @_;
498              
499 2         12 $self->{_exclude} = $self->_compile_regex($exclude);
500              
501 2         16 return $self;
502             }
503              
504             =head2 get_exclude
505              
506             $regexp = $obj->get_exclude
507              
508             Returns the exclude regular expression.
509              
510             Note that this may not be identical to what was passed in.
511              
512             =cut
513              
514 14     14 1 1188 sub get_exclude { $_[0]->{_exclude} }
515              
516             # Return a compiled regex from a string or regex
517             sub _compile_regex {
518 6     6   14 my($self, $regex) = @_;
519              
520 6 100       21 if (defined $regex) {
521 4 50       16 if (ref $regex) {
522 4 100       180 croak "Regexp or string required"
523             if ref $regex ne 'Regexp';
524             }
525             else {
526 0         0 $regex = qr($regex);
527             }
528             }
529              
530 5         14 return $regex;
531             }
532              
533             # Apply include and exclude rules to a list of view names
534             sub _filter_views {
535 14     14   34 my($self, @views) = @_;
536              
537 14         54 my $include = $self->get_include;
538 14         55 my $exclude = $self->get_exclude;
539              
540 14 100       46 @views = grep { $_ =~ $include } @views if $include;
  4         25  
541 14 100       35 @views = grep { $_ !~ $exclude } @views if $exclude;
  2         12  
542              
543 14         52 return @views;
544             }
545              
546             =head2 set_base_classes
547              
548             $obj = $obj->set_base_classes(@classes)
549              
550             Sets classes for all generated classes to inherit from.
551              
552             This is in addition to the class specified by the driver's base_class method,
553             which will always be the first item in the generated @ISA.
554              
555             Note that these classes are not loaded for you, be sure to C or C
556             them yourself.
557              
558             =cut
559              
560             sub set_base_classes {
561 2     2 1 2250 my $self = shift;
562              
563             # We might get a ref from new()
564 2 50       11 my @classes = ref $_[0] ? @{$_[0]} : @_;
  0         0  
565              
566 2         6 $self->{_base_classes} = \@classes;
567              
568 2         9 return $self;
569             }
570              
571             =head2 add_base_classes
572              
573             $obj = $obj->add_base_classes(@classes)
574              
575             Appends to the list of base classes.
576              
577             =cut
578              
579             sub add_base_classes {
580 0     0 1 0 my($self, @new) = @_;
581              
582 0         0 return $self->set_base_classes($self->get_base_classes, @new);
583             }
584              
585             =head2 get_base_classes
586              
587             @classes = $obj->get_base_classes
588              
589             Returns the list of base classes, as supplied by set_base_classes.
590              
591             =cut
592              
593             sub get_base_classes {
594 23 100   23 1 102 return @{$_[0]->{_base_classes} || []}
  23         144  
595             }
596              
597             =head2 set_left_base_classes
598              
599             Sets base classes like set_base_classes, except that the added classes will go
600             before the driver's base_class.
601              
602             =cut
603              
604             sub set_left_base_classes {
605 4     4 1 5 my $self = shift;
606              
607             # We might get a ref from new()
608 4 50       17 my @classes = ref $_[0] ? @{$_[0]} : @_;
  0         0  
609              
610 4         10 $self->{_left_base_classes} = \@classes;
611              
612 4         22 return $self;
613             }
614              
615             =head2 get_left_base_classes
616              
617             @classes = $obj->get_left_base_classes
618              
619             Returns the list of left base classes, as supplied by set_base_classes.
620              
621             =cut
622              
623             sub get_left_base_classes {
624 27     27 1 184 my $self = shift;
625              
626 27 100       43 return @{ $self->{_left_base_classes} || [] }
  27         201  
627             }
628              
629             =head2 add_left_base_classes
630              
631             $obj = $obj->add_base_classes(@classes)
632              
633             Appends to the list of left base classes.
634              
635             =cut
636              
637             sub add_left_base_classes {
638 4     4 1 104 my ($self, @new) = @_;
639              
640 4         18 return $self->set_left_base_classes($self->get_left_base_classes, @new);
641             }
642              
643             sub _get_all_base_classes {
644 23     23   32 my $self = shift;
645              
646 23         62 return reverse($self->get_left_base_classes),
647             $self->base_class,
648             $self->get_base_classes,
649             }
650              
651             =head2 set_import_classes
652              
653             $obj = $obj->set_import_classes(@classes)
654              
655             Sets a list of classes to import from. Note that these classes are not loaded by
656             the generated class itself.
657              
658             # Load the module first
659             require Class::DBI::Plugin::RetrieveAll;
660            
661             # Make generated classes import symbols
662             $loader->set_import_classes(qw(Class::DBI::Plugin::RetrieveAll));
663              
664             Any classes that inherit from Exporter will be loaded via Exporter's C
665             function. Any other classes are loaded by a C call in a string eval.
666              
667             =cut
668              
669             sub set_import_classes {
670 3     3 1 7 my $self = shift;
671              
672             # We might get a ref from new()
673 3 100       18 my @classes = ref $_[0] ? @{$_[0]} : @_;
  1         3  
674              
675 3         9 $self->{_import_classes} = \@classes;
676              
677 3         11 return $self;
678             }
679              
680             =head2 add_import_classes
681              
682             $obj = $obj->add_import_classes(@classes)
683              
684             Appends to the list of import classes.
685              
686             =cut
687              
688             sub add_import_classes {
689 0     0 1 0 my($self, @new) = @_;
690              
691 0         0 return $self->set_import_classes($self->get_import_classes, @new);
692             }
693              
694             =head2 get_import_classes
695              
696             @classes = $obj->get_import_classes
697              
698             Returns the list of classes that will be imported into you generated classes.
699              
700             =cut
701              
702 23 100   23 1 32 sub get_import_classes { @{$_[0]->{_import_classes} || []} }
  23         181  
703              
704             =head2 set_accessor_prefix
705              
706             $obj = $obj->set_accessor_prefix
707              
708             Sets the accessor prefix for generated classes. See L for details of
709             how this works.
710              
711             =cut
712              
713             sub set_accessor_prefix {
714 1     1 1 2 my($self, $prefix) = @_;
715              
716 1         4 $self->{_accessor} = "$prefix";
717              
718 1         10 return $self;
719             }
720              
721             =head2 get_accessor_prefix
722              
723             $prefix = $obj->get_accessor_prefix
724              
725             Returns the object's accessor prefix.
726              
727             =cut
728              
729 23     23 1 97 sub get_accessor_prefix { $_[0]->{_accessor} }
730              
731             =head2 set_mutator_prefix
732              
733             $obj = $obj->set_mutator_prefix
734              
735             Sets the mutator prefix for generated classes. See L for details of
736             how this works.
737              
738             =cut
739              
740             sub set_mutator_prefix {
741 1     1 1 4 my($self, $prefix) = @_;
742              
743 1         5 $self->{_mutator} = "$prefix";
744              
745 1         45 return $self;
746             }
747              
748             =head2 get_mutator_prefix
749              
750             $prefix = $obj->get_mutator_prefix
751              
752             Returns the object's mutator prefix.
753              
754             =cut
755              
756 23     23 1 105 sub get_mutator_prefix { $_[0]->{_mutator} }
757              
758             =head1 METHODS
759              
760             =head2 load_views
761              
762             @classes = $obj->load_views
763              
764             The main method for the class, loads all relevant views from the database and
765             generates classes for those views.
766              
767             The generated classes will be read-only and have a multi-column primary key
768             containing every column. This is because it is not guaranteed that the view will
769             have a real primary key and Class::DBI insists that there should be a unique
770             identifier for every row.
771              
772             If the newly generated class inherits a "Main" Class::DBI handle (via
773             C or C calls in base classes) that handle will be used by
774             the class. Otherwise, a new connection is set up for the classes based on the
775             loader's connection.
776              
777             Usually, any row containing an undef (NULL) primary key column is considered
778             false in boolean context, in this particular case however that doesn't make much
779             sense. So only all-null rows are considered false in classes generated by this
780             class.
781              
782             Each class is only ever generated once, no matter how many times load_views() is
783             called. If you want to load the same view twice for some reason, you can achieve
784             this by changing the namespace.
785              
786             Returns class names for all created classes.
787              
788             =cut
789              
790             sub load_views {
791 14     14 1 16138 my $self = shift;
792              
793 14         67 my @views = $self->get_views;
794              
795 14         249 my @classes;
796              
797 14         177 for my $view ($self->_filter_views(@views)) {
798 26         140 my @cols = $self->get_view_cols($view);
799              
800 26 100       354 if (@cols) {
801 25         83 push @classes, $self->_create_class($view, @cols);
802             }
803             else {
804 1         128 carp "No columns found in $view, skipping\n";
805             }
806             }
807              
808             # load all symbols into all classes in a single call.
809 14         63 $self->_do_eval;
810              
811 13         970 return @classes;
812             }
813              
814             # Set up the view class.
815             sub _create_class {
816 25     25   67 my($self, $view, @columns) = @_;
817              
818 25         190 my $class = $self->view_to_class($view);
819              
820             # Don't load the same class twice
821 25 100       115 return if $class_cache{$class}++;
822              
823             {
824 7     7   73 no strict 'refs';
  7         14  
  7         2529  
  23         38  
825              
826 23         151 @{$class.'::ISA'} = $self->_get_all_base_classes;
  23         928  
827              
828             # We only want all-null primary keys to be considered false.
829             # (This method is used by the bool overloader)
830 23         230 *{$class.'::_undefined_primary'} = sub {
831 3     3   6442 my $self = shift;
832 3         81 my @cols = $self->_attrs($self->primary_columns);
833 3         142 my @undef = grep { not defined } @cols;
  9         18  
834              
835 3 100       21 return @undef == @cols ? 1 : 0;
836 23         142 };
837             }
838              
839 23         90 $self->_setup_accessors($class);
840              
841             # Only set up the connection explicitly if needed.
842 23 100       494 unless ($class->can('db_Main')) {
843 12         45 $class->connection($self->_get_dbi_args);
844             }
845              
846             # Prevent attempts to write to views
847 23         3152 $class->make_read_only;
848              
849 23         5096 $class->table($view);
850              
851             # We probably won't have a primary key,
852             # use a multi-column primary key containing all rows
853 23         1445 $class->columns(Primary => @columns);
854              
855 23         17043 $self->_do_imports($class);
856              
857 23         246 return $class;
858             }
859              
860             # Handle different Class::DBI accessor / mutator name interfaces
861              
862             our ($_accessor_method, $_mutator_method);
863             sub __detect_version {
864 12     12   10634 my $v = $Class::DBI::VERSION;
865              
866 12         27 $_accessor_method = 'accessor_name';
867 12         114 $_mutator_method = 'mutator_name';
868              
869 12 100       67 if (ref $v eq 'version') {
870 11 100       540 if ($v >= version->new(3.0.7)) {
871 9         27 $_accessor_method = 'accessor_name_for';
872 9         434 $_mutator_method = 'mutator_name_for';
873             }
874             }
875             }
876 7     7   30 BEGIN { __detect_version() }
877              
878             sub _setup_accessors {
879 23     23   51 my ($self, $class) = @_;
880              
881 7     7   41 no strict 'refs';
  7         17  
  7         6024  
882              
883 23 100       75 if (defined(my $accessor = $self->get_accessor_prefix)) {
884 2         6 my $method = "$class\::$_accessor_method";
885              
886             *$method = sub {
887 6     6   2070 my ($self, $col) = @_;
888 6         25 return $accessor . $col;
889 2         14 };
890             }
891              
892 23 100       69 if (defined(my $mutator = $self->get_mutator_prefix)) {
893 2         6 my $method = "$class\::$_mutator_method";
894              
895             *$method = sub {
896 6     6   69 my ($self, $col) = @_;
897 6         16 return $mutator . $col;
898 2         15 };
899             }
900              
901 23         45 return $self;
902             }
903              
904             # import symbols into the target namespace. Try to avoid string eval when
905             # possible. This eval code is cached by _set_eval and can be executed with
906             # _do_eval
907             sub _do_imports {
908 23     23   45 my($self, $class) = @_;
909              
910 23 100       83 my @imports = $self->get_import_classes or return $self;
911              
912 8         17 my @manual;
913 8         15 for my $module (@imports) {
914 12 100       111 if (isa($module, 'Exporter')) {
    50          
915             # use Exporter's export method, avoid string eval
916 4         368 $module->export($class);
917             }
918             elsif (can($module, 'import')) {
919 8         25 push @manual, $module;
920             }
921             else {
922 0         0 carp "$module has no import function";
923             }
924             }
925              
926 8 50       24 if (@manual) {
927             # load classes via string eval (yuk!)
928 8         33 $self->_set_eval($class, @manual);
929             }
930              
931 8         19 return $self;
932             }
933              
934             # cache code to eval to minimise string eval calls
935             sub _set_eval {
936 8     8   18 my ($self, $class, @manual) = @_;
937              
938 8         33 my $code = join("\n",
939             "package $class;",
940 8         24 map {"use $_;"} @manual
941             );
942              
943 8         14 push @{$self->{__eval_cache}}, $code;
  8         34  
944             }
945              
946             # process pending eval code and reset
947             sub _do_eval {
948 14     14   26 my $self = shift;
949              
950 14         35 my $cache = delete $self->{__eval_cache};
951              
952 14 100       41 if (defined $cache) {
953 4         14 my $code = join("\n\n", @$cache);
954              
955 4     2   402 eval $code;
  2     2   558  
  2     2   138  
  2     1   22  
  2         237  
  2         5  
  2         9  
  2         462  
  1         2  
  1         6  
  1         63  
  1         2  
  1         4  
956              
957 4 100       273 croak "Eval error!\nCode:\n$code\n\nMessage: $@" if $@;
958             }
959              
960 13         165 return $self;
961             }
962              
963             =head2 view_to_class
964              
965             $class = $obj->view_to_class($view)
966              
967             Returns the class for the given view name. This depends on the object's current
968             namespace, see set_namespace(). It doesn't matter if the class has been loaded,
969             or if the view exists in the database.
970              
971             If this method is called without arguments, or with an empty string, it returns
972             an empty string.
973              
974             =cut
975              
976             sub view_to_class {
977 28     28 1 878 my($self, $view) = @_;
978              
979 28 100 100     179 if (defined $view and length $view) {
980             # cribbed from Class::DBI::Loader
981 26         347 $view = join('', map { ucfirst } split(/[\W_]+/, $view));
  52         322  
982              
983 26         96 return join('::', $self->get_namespace, $view);
984             }
985             else {
986 2         11 return '';
987             }
988             }
989              
990             =head2 _get_dbi_handle
991              
992             $dbh = $obj->_get_dbi_handle
993              
994             Returns a DBI handle based on the object's dsn, username and password. This
995             generally shouldn't be called externally (hence the leading underscore).
996              
997             Making multiple calls to this method won't cause multiple connections to be
998             made. A single handle is cached by the object from the first call to
999             _get_dbi_handle until such time as the object goes out of scope or set_dsn is
1000             called again, at which time the handle is disconnected and the cache is cleared.
1001              
1002             If the connection fails, a fatal error is raised.
1003              
1004             =head2 _clear_dbi_handle
1005              
1006             $obj->_clear_dbi_handle
1007              
1008             This is the cleanup method for the object's DBI handle. It is called whenever
1009             the DBI handle needs to be closed down. i.e. when a new handle is used or the
1010             object goes out of scope. Subclasses should override this method if they need to
1011             clean up any state data that relies on the current database connection, like
1012             statement handles for example. If you don't want the handle that the object is
1013             using to be disconnected, use the _set_keepalive method.
1014              
1015             sub _clear_dbi_handle {
1016             my $self = shift;
1017              
1018             delete $self->{statement_handle};
1019              
1020             $self->SUPER::_clear_dbi_handle(@_);
1021             }
1022              
1023             =head2 _set_dbi_handle
1024              
1025             $obj = $obj->_set_dbi_handle($dbh)
1026              
1027             This method is used to attach a DBI handle to the object. It might prove useful
1028             to use this method in order to use an existing database connection in the loader
1029             object. Note that unlike set_dsn, calling this method directly will not cause an
1030             appropriate driver to be loaded. See _load_driver for that.
1031              
1032             =head2 _set_keepalive
1033              
1034             $obj = $obj->_set_keepalive($bool)
1035              
1036             When set to true, the database handle used by the object won't be disconnected automatically.
1037              
1038             =head2 _load_driver
1039              
1040             $obj = $obj->_load_driver($driver_name)
1041              
1042             This method is used internally by set_dsn to load a driver to handle
1043             database-specific functionality. It can be called directly in conjunction with
1044             _set_dbi_handle to load views from an existing database connection.
1045              
1046             =head1 DRIVER METHODS
1047              
1048             The following methods are provided by the relevant driver classes. If they are
1049             called on a native Class::DBI::ViewLoader object (one without a dsn set), they
1050             will cause fatal errors. They are documented here for the benefit of driver
1051             writers but they may prove useful for users also.
1052              
1053             =over 4
1054              
1055             =item * base_class
1056              
1057             $class = $driver->base_class
1058              
1059             Should return the name of the base class to be used by generated classes. This
1060             will generally be a Class::DBI driver class.
1061              
1062             package Class::DBI::ViewLoader::Pg;
1063              
1064             # Generate postgres classes
1065             sub base_class { "Class::DBI::Pg" }
1066              
1067             =item * get_views
1068              
1069             @views = $driver->get_views;
1070              
1071             Should return the names of all the views in the current database.
1072              
1073             =item * get_view_cols
1074              
1075             @columns = $driver->get_view_cols($view);
1076              
1077             Should return the names of all the columns in the given view.
1078              
1079             =back
1080              
1081             A list of these methods is provided by this class, in
1082             @Class::DBI::ViewLoader::driver_methods, so that each driver can be sure that it
1083             is implementing all required methods. The provided t/04..plugin.t is a
1084             self-contained test script that checks a driver for compatibility with the
1085             current version of Class::DBI::ViewLoader, driver writers should be able to copy
1086             the test into their distribution and edit the driver name to provide basic
1087             compliance tests.
1088              
1089             =cut
1090              
1091             our @driver_methods = qw(
1092             base_class
1093             get_views
1094             get_view_cols
1095             );
1096              
1097             for my $method (@driver_methods) {
1098 7     7   59 no strict 'refs';
  7         13  
  7         1143  
1099 6     6   8380 *$method = sub { $_[0]->_refer_to_handler($method) };
1100             }
1101              
1102             sub _refer_to_handler {
1103 6     6   15 my($self, $sub) = @_;
1104 6         10 my $handler = ref $self;
1105              
1106 6 100       42 if ($handler eq __PACKAGE__) {
1107             # We haven't reblessed into a subclass
1108 3         444 confess "No handler loaded, try calling set_dsn() first";
1109             }
1110             else {
1111 3         391 confess "$sub not overridden by $handler";
1112             }
1113             }
1114              
1115             1;
1116              
1117             __END__