File Coverage

blib/lib/Class/DBI/ViewLoader.pm
Criterion Covered Total %
statement 271 271 100.0
branch 91 92 98.9
condition 6 6 100.0
subroutine 67 67 100.0
pod 30 30 100.0
total 465 466 99.7


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