ViewLoader.pm

filter: Statementstmt 99.6% 280 / 281 Branchbran 96.5% 83 / 86 Conditioncond 100% 12 / 12 MC/DCmcdc 100% 7 / 7 Subroutinesub 100% 67 / 67 Podpod 100% 30 / 30 totaltotal 99.1% 479 / 483 CC 53 SCAR 9.3
CC
53
Cov
99%
_do_imports
7.3
new
5.0
_compat
4.0
CRAP 2.5
« ViewLoader/Auto.pm ↑ Summary
1 package Class::DBI::ViewLoader;
2  
3 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 7 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<Class::DBI> classes. It follows
55 roughly the same interface employed by L<Class::DBI::Loader>.
56  
57 This class behaves as a base class for the database-dependent driver classes,
58 which are loaded by L<Module::Pluggable>. 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::E<lt>driver_nameE<gt>.
61  
62 =cut
63  
64 7 ▶use Module::Pluggable (
Subroutine BEGIN: called CC=1 SCAR=0.0
65 7 search_path => __PACKAGE__,
66 require => 1,
67 inner => 0
68 7 );
69  
70 7 ▶use Class::DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
71 7 ▶use DBI 1.43;
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 7 ▶use Carp qw( carp croak confess );
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 7 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 7 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<Class::DBI::Loader>, 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 7 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 23 ▶sub new {
Subroutine new: called CC=5 SCAR=16.1
Pod documented
137 23 my($class, %args) = @_;
138  
139 23 my $self = bless {}, $class;
140  
141 # Do dsn first, as we may be reblessed
142 23 ▶ if ($args{'dsn'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"dsn"}) 11 12 23
143 11 $self->set_dsn(delete $args{'dsn'});
144 }
145  
146 20 $self->_compat(\%args);
147  
148 20 for my $arg (keys %args) {
149 35 ▶ if (my $setter = $self->can("set_$arg")) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $setter = $self->can("set_$arg")) 34 1 35
150 34 &$setter($self, delete $args{$arg});
151 }
152 }
153  
154 20 ▶ if (%args) {
Branch: 1 branch
BranchTrueFalseTotal
if (%args) 1 19 20
155 # All supported arguments should have been deleted
156 1 my $extra = join(', ', map {"'$_'"} sort keys %args);
157 1 croak "Unrecognised arguments in new: $extra";
158 }
159  
160 19 return $self;
161 }
162  
163 26 ▶sub _compat {
Subroutine _compat: called CC=4 SCAR=13.9
164 26 my ($self, $args) = @_;
165  
166 26 for my $arg (keys %$args) {
167 44 ▶ if (defined $compat{$arg}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $compat{$arg}) 6 38 44
168 6 my $value = delete $args->{$arg};
169  
170 # silently skip unsupported Class::DBI::Loader args
171 6 ▶ $arg = $compat{$arg} or next;
Branch: 1 branch
BranchTrueFalseTotal
$arg = $compat{$arg} or next 4 2 6
172 4 $args->{$arg} = $value;
173 }
174 }
175  
176 26 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<DBI> 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 18 ▶sub set_dsn {
Subroutine set_dsn: called CC=3 SCAR=11.0
Pod documented
195 18 my($self, $dsn) = @_;
196  
197 18 ▶ croak "No dsn" unless $dsn;
Branch: 1 branch
BranchTrueFalseTotal
unless $dsn 1 17 18
198  
199 17 ▶ my $driver = (DBI->parse_dsn($dsn))[1]
Branch: 1 branch
BranchTrueFalseTotal
my $driver = ("DBI"->parse_dsn($dsn))[1] or croak("Invalid dsn '${dsn}'") 16 1 17
200 or croak "Invalid dsn '$dsn'";
201  
202 16 $self->_load_driver($driver)->{_dsn} = $dsn;
203  
204 14 return $self;
205 }
206  
207 # rebless into driver class
208 20 ▶sub _load_driver {
Subroutine _load_driver: called CC=3 SCAR=11.0
209 20 my ($self, $driver) = @_;
210  
211 20 my $handler = $handlers{$driver};
212  
213 20 ▶ if ($handler) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handler) { } 19 1 20
214 19 ▶ if ($handler->isa(__PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handler->isa(__PACKAGE__)) { } 18 1 19
215 # rebless into handler class
216 18 bless $self, $handler;
217 }
218 else {
219 1 confess "$handler is not a ".__PACKAGE__." subclass";
220 }
221 }
222 else {
223 1 croak "No handler for driver '$driver'";
224 }
225  
226 18 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 ▶sub get_dsn { $_[0]->{_dsn} }
Subroutine get_dsn: called CC=1 SCAR=0.0
Pod documented
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 6 ▶sub set_username {
Subroutine set_username: called CC=2 SCAR=6.9
Pod documented
248 6 my($self, $user) = @_;
249  
250 # force stringification
251 6 ▶ $user = "$user" if defined $user;
Branch: 1 branch
BranchTrueFalseTotal
if defined $user 5 1 6
252  
253 6 $self->{_username} = $user;
254  
255 6 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 ▶sub get_username { $_[0]->{_username} }
Subroutine get_username: called CC=1 SCAR=0.0
Pod documented
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 6 ▶sub set_password {
Subroutine set_password: called CC=2 SCAR=6.9
Pod documented
277 6 my($self, $pass) = @_;
278  
279 # force stringification
280 6 ▶ $pass = "$pass" if defined $pass;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pass 5 1 6
281  
282 6 $self->{_password} = $pass;
283  
284 6 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 ▶sub get_password { $_[0]->{_password} }
Subroutine get_password: called CC=1 SCAR=0.0
Pod documented
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<DBI>.
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 4 ▶sub set_options {
Subroutine set_options: called CC=2 SCAR=6.9
Pod documented
314 4 my $self = shift;
315 4 ▶ my $opts = { ref $_[0] ? %{ $_[0] } : @_ };
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 2 2 4
316  
317 4 $self->{_dbi_options} = $opts;
318  
319 4 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 4 ▶sub get_options {
Subroutine get_options: called CC=2 SCAR=6.9
Pod documented
335 4 my $self = shift;
336  
337 # set up an empty options hash if there is none available.
338 4 ▶ $self->set_options unless $self->{_dbi_options};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_dbi_options"} 1 3 4
339  
340 4 return $self->{_dbi_options};
341 }
342  
343 # Return this object's complete arguments to send to DBI.
344 14 ▶sub _get_dbi_args {
Subroutine _get_dbi_args: called CC=1 SCAR=0.0
345 14 my $self = shift;
346  
347 # breaking encapsulation to use hashslice:
348 14 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 3 ▶sub _get_dbi_handle {
Subroutine _get_dbi_handle: called CC=3 SCAR=11.0
354 3 my $self = shift;
355  
356 3 ▶ return $self->{_dbh} if $self->{_dbh};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_dbh"} 1 2 3
357  
358 2 ▶ my $dbh = DBI->connect( $self->_get_dbi_args )
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = "DBI"->connect($self->_get_dbi_args) or croak("Couldn't connect to database, $DBI::errstr") 1 1 2
359 or croak "Couldn't connect to database, $DBI::errstr";
360  
361 1 $self->_set_dbi_handle($dbh);
362  
363 1 return $dbh;
364 }
365  
366 # set the DBI handle. Might one day be called directly..
367 5 ▶sub _set_dbi_handle {
Subroutine _set_dbi_handle: called CC=1 SCAR=0.0
368 5 my $self = shift;
369 5 my $dbh = shift;
370  
371 5 $self->_clear_dbi_handle;
372 5 $self->{_dbh} = $dbh;
373  
374 5 return $self;
375 }
376  
377 # disconnect current DBI handle, if any
378 28 ▶sub _clear_dbi_handle {
Subroutine _clear_dbi_handle: called CC=3 SCAR=11.0
379 28 my $self = shift;
380  
381 28 ▶ return $self if $self->_keepalive;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_keepalive 4 24 28
382  
383 24 ▶ if (defined $self->{_dbh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"_dbh"}) 1 23 24
384 1 delete($self->{_dbh})->disconnect;
385 }
386  
387 24 return $self;
388 }
389  
390 23 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
391 23 my $self = shift;
392  
393 23 $self->_clear_dbi_handle;
394 }
395  
396 # switch to disable _clear_dbi_handle
397 4 ▶sub _set_keepalive {
Subroutine _set_keepalive: called CC=1 SCAR=0.0
398 4 my $self = shift;
399 4 $self->{__keepalive} = shift;
400 4 return $self;
401 }
402  
403 # check status of switch
404 28 ▶sub _keepalive {
Subroutine _keepalive: called CC=1 SCAR=0.0
405 28 my $self = shift;
406 28 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 16 ▶sub set_namespace {
Subroutine set_namespace: called CC=1 SCAR=0.0
Pod documented
419 16 my($self, $namespace) = @_;
420  
421 16 $namespace =~ s/::$//;
422  
423 16 $self->{_namespace} = $namespace;
424  
425 16 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 30 ▶sub get_namespace {
Subroutine get_namespace: called CC=3 SCAR=11.0
Pod documented
437 30 my $self = shift;
438 30 my $out = $self->{_namespace};
439  
440 30 ▶ if (defined $out and length $out) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $out and length $out) { } 26 4 30
Condition100%3/3
defined $out and length $out
!ll&&!rl&&r
3126
MC/DC100%2/2
defined $out and length $out
defined $out length $out
Truth table100%3/3
A and B
A= defined $outB= length $out
ABresult
0X0
100
111
441 26 return $out;
442 }
443 else {
444 4 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 8 ▶sub set_include {
Subroutine set_include: called CC=1 SCAR=0.0
Pod documented
461 8 my($self, $include) = @_;
462  
463 8 $self->{_include} = $self->_compile_regex($include);
464  
465 7 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 ▶sub get_include { $_[0]->{_include} }
Subroutine get_include: called CC=1 SCAR=0.0
Pod documented
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 6 ▶sub set_exclude {
Subroutine set_exclude: called CC=1 SCAR=0.0
Pod documented
495 6 my($self, $exclude) = @_;
496  
497 6 $self->{_exclude} = $self->_compile_regex($exclude);
498  
499 6 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 ▶sub get_exclude { $_[0]->{_exclude} }
Subroutine get_exclude: called CC=1 SCAR=0.0
Pod documented
513  
514 # Return a compiled regex from a string or regex
515 14 ▶sub _compile_regex {
Subroutine _compile_regex: called CC=4 SCAR=13.9
516 14 my($self, $regex) = @_;
517  
518 14 ▶ if (defined $regex) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $regex) 10 4 14
519 10 ▶ if (ref $regex) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $regex) { } 4 6 10
520 4 ▶ croak "Regexp or string required"
Branch: 1 branch
BranchTrueFalseTotal
if ref $regex ne "Regexp" 1 3 4
521 if ref $regex ne 'Regexp';
522 }
523 else {
524 6 $regex = qr($regex);
525 }
526 }
527  
528 13 return $regex;
529 }
530  
531 # Apply include and exclude rules to a list of view names
532 14 ▶sub _filter_views {
Subroutine _filter_views: called CC=3 SCAR=11.0
533 14 my($self, @views) = @_;
534  
535 14 my $include = $self->get_include;
536 14 my $exclude = $self->get_exclude;
537  
538 14 ▶ @views = grep { $_ =~ $include } @views if $include;
Branch: 1 branch
BranchTrueFalseTotal
if $include 2 12 14
539 14 ▶ @views = grep { $_ !~ $exclude } @views if $exclude;
Branch: 1 branch
BranchTrueFalseTotal
if $exclude 1 13 14
540  
541 14 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<use> or C<require>
554 them yourself.
555  
556 =cut
557  
558 7 ▶sub set_base_classes {
Subroutine set_base_classes: called CC=2 SCAR=6.9
Pod documented
559 7 my $self = shift;
560  
561 # We might get a ref from new()
562 7 ▶ my @classes = ref $_[0] ? @{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 1 6 7
563  
564 7 $self->{_base_classes} = \@classes;
565  
566 7 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 1 ▶sub add_base_classes {
Subroutine add_base_classes: called CC=1 SCAR=0.0
Pod documented
578 1 my($self, @new) = @_;
579  
580 1 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 30 ▶sub get_base_classes {
Subroutine get_base_classes: called CC=2 SCAR=6.9
Pod documented
592 30 ▶ return @{$_[0]->{_base_classes} || []}
Condition100%2/2
$_[0]{'_base_classes'} || []
l!l
1218
MC/DC100%1/1
$_[0]{'_base_classes'} || []
$_[0]{'_base_classes'}
Truth table100%2/2
A
A= $_[0]{'_base_classes'}
Aresult
11
00
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 9 ▶sub set_left_base_classes {
Subroutine set_left_base_classes: called CC=2 SCAR=6.9
Pod documented
603 9 my $self = shift;
604  
605 # We might get a ref from new()
606 9 ▶ my @classes = ref $_[0] ? @{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 2 7 9
607  
608 9 $self->{_left_base_classes} = \@classes;
609  
610 9 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 34 ▶sub get_left_base_classes {
Subroutine get_left_base_classes: called CC=2 SCAR=6.9
Pod documented
622 34 my $self = shift;
623  
624 34 ▶ return @{ $self->{_left_base_classes} || [] }
Condition100%2/2
$self->{'_left_base_classes'} || []
l!l
1321
MC/DC100%1/1
$self->{'_left_base_classes'} || []
$self->{'_left_base_classes'}
Truth table100%2/2
A
A= $self->{'_left_base_classes'}
Aresult
11
00
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 5 ▶sub add_left_base_classes {
Subroutine add_left_base_classes: called CC=1 SCAR=0.0
Pod documented
636 5 my ($self, @new) = @_;
637  
638 5 return $self->set_left_base_classes($self->get_left_base_classes, @new);
639 }
640  
641 25 ▶sub _get_all_base_classes {
Subroutine _get_all_base_classes: called CC=1 SCAR=0.0
642 25 my $self = shift;
643  
644 25 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<export>
663 function. Any other classes are loaded by a C<use> call in a string eval.
664  
665 =cut
666  
667 7 ▶sub set_import_classes {
Subroutine set_import_classes: called CC=2 SCAR=6.9
Pod documented
668 7 my $self = shift;
669  
670 # We might get a ref from new()
671 7 ▶ my @classes = ref $_[0] ? @{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 2 5 7
672  
673 7 $self->{_import_classes} = \@classes;
674  
675 7 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 1 ▶sub add_import_classes {
Subroutine add_import_classes: called CC=1 SCAR=0.0
Pod documented
687 1 my($self, @new) = @_;
688  
689 1 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 ▶sub get_import_classes { @{$_[0]->{_import_classes} || []} }
Subroutine get_import_classes: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{'_import_classes'} || []
l!l
1316
MC/DC100%1/1
$_[0]{'_import_classes'} || []
$_[0]{'_import_classes'}
Truth table100%2/2
A
A= $_[0]{'_import_classes'}
Aresult
11
00
701  
702 =head2 set_accessor_prefix
703  
704 $obj = $obj->set_accessor_prefix
705  
706 Sets the accessor prefix for generated classes. See L<Class::DBI> for details of
707 how this works.
708  
709 =cut
710  
711 3 ▶sub set_accessor_prefix {
Subroutine set_accessor_prefix: called CC=1 SCAR=0.0
Pod documented
712 3 my($self, $prefix) = @_;
713  
714 3 $self->{_accessor} = "$prefix";
715  
716 3 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 ▶sub get_accessor_prefix { $_[0]->{_accessor} }
Subroutine get_accessor_prefix: called CC=1 SCAR=0.0
Pod documented
728  
729 =head2 set_mutator_prefix
730  
731 $obj = $obj->set_mutator_prefix
732  
733 Sets the mutator prefix for generated classes. See L<Class::DBI> for details of
734 how this works.
735  
736 =cut
737  
738 3 ▶sub set_mutator_prefix {
Subroutine set_mutator_prefix: called CC=1 SCAR=0.0
Pod documented
739 3 my($self, $prefix) = @_;
740  
741 3 $self->{_mutator} = "$prefix";
742  
743 3 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 ▶sub get_mutator_prefix { $_[0]->{_mutator} }
Subroutine get_mutator_prefix: called CC=1 SCAR=0.0
Pod documented
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<connection> or C<set_db> 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 14 ▶sub load_views {
Subroutine load_views: called CC=3 SCAR=11.0
Pod documented
789 14 my $self = shift;
790  
791 14 my @views = $self->get_views;
792  
793 14 my @classes;
794  
795 14 for my $view ($self->_filter_views(@views)) {
796 26 my @cols = $self->get_view_cols($view);
797  
798 26 ▶ if (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) { } 25 1 26
799 25 push @classes, $self->_create_class($view, @cols);
800 }
801 else {
802 1 carp "No columns found in $view, skipping\n";
803 }
804 }
805  
806 # load all symbols into all classes in a single call.
807 14 $self->_do_eval;
808  
809 13 return @classes;
810 }
811  
812 # Set up the view class.
813 25 ▶sub _create_class {
Subroutine _create_class: called CC=3 SCAR=11.0
814 25 my($self, $view, @columns) = @_;
815  
816 25 my $class = $self->view_to_class($view);
817  
818 # Don't load the same class twice
819 25 ▶ return if $class_cache{$class}++;
Branch: 1 branch
BranchTrueFalseTotal
if $Class::DBI::ViewLoader::class_cache{$class}++ 2 23 25
820  
821 {
822 7 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
823  
824 23 @{$class.'::ISA'} = $self->_get_all_base_classes;
825  
826 # We only want all-null primary keys to be considered false.
827 # (This method is used by the bool overloader)
828 23 ▶ *{$class.'::_undefined_primary'} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
829 3 my $self = shift;
830 3 my @cols = $self->_attrs($self->primary_columns);
831 3 my @undef = grep { not defined } @cols;
832  
833 3 ▶ return @undef == @cols ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@undef == @cols ? : 1 2 3
834 23 };
835 }
836  
837 23 $self->_setup_accessors($class);
838  
839 # Only set up the connection explicitly if needed.
840 23 ▶ unless ($class->can('db_Main')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("db_Main")) 12 11 23
841 12 $class->connection($self->_get_dbi_args);
842 }
843  
844 # Prevent attempts to write to views
845 23 $class->make_read_only;
846  
847 23 $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 $class->columns(Primary => @columns);
852  
853 23 $self->_do_imports($class);
854  
855 23 return $class;
856 }
857  
858 # Handle different Class::DBI accessor / mutator name interfaces
859  
860 7 our ($_accessor_method, $_mutator_method);
861 12 ▶sub __detect_version {
Subroutine __detect_version: called CC=3 SCAR=11.0
862 12 my $v = $Class::DBI::VERSION;
863  
864 12 $_accessor_method = 'accessor_name';
865 12 $_mutator_method = 'mutator_name';
866  
867 12 ▶ if (ref $v eq 'version') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "version") 11 1 12
868 11 ▶ if ($v >= version->new(3.0.7)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v >= "version"->new(3.0.7)) 9 2 11
869 9 $_accessor_method = 'accessor_name_for';
870 9 $_mutator_method = 'mutator_name_for';
871 }
872 }
873 }
874 7 ▶BEGIN { __detect_version() }
Subroutine BEGIN: called CC=1 SCAR=0.0
875  
876 23 ▶sub _setup_accessors {
Subroutine _setup_accessors: called CC=3 SCAR=11.0
877 23 my ($self, $class) = @_;
878  
879 7 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
880  
881 23 ▶ if (defined(my $accessor = $self->get_accessor_prefix)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $accessor = $self->get_accessor_prefix)) 2 21 23
882 2 my $method = "$class\::$_accessor_method";
883  
884 6 ▶ *$method = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
885 6 my ($self, $col) = @_;
886 6 return $accessor . $col;
887 2 };
888 }
889  
890 23 ▶ if (defined(my $mutator = $self->get_mutator_prefix)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $mutator = $self->get_mutator_prefix)) 2 21 23
891 2 my $method = "$class\::$_mutator_method";
892  
893 6 ▶ *$method = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
894 6 my ($self, $col) = @_;
895 6 return $mutator . $col;
896 2 };
897 }
898  
899 23 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 23 ▶sub _do_imports {
Subroutine _do_imports: called CC=7 SCAR=19.9
906 23 my($self, $class) = @_;
907  
908 23 ▶ my @imports = $self->get_import_classes or return $self;
Branch: 1 branch
BranchTrueFalseTotal
my(@imports) = $self->get_import_classes or return $self 8 15 23
909  
910 8 my @manual;
911 8 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 ▶ next if ref $module;
Branch: 1 branch
BranchTrueFalseTotal
if ref $module 0 12 12
915  
916 12 ▶ if ($module->isa('Exporter')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($module->isa('Exporter')) { } 4 8 12
elsif ($module->can('import')) { } 8 0 8
917 # use Exporter's export method, avoid string eval
918 4 $module->export($class);
919 }
920 elsif ($module->can('import')) {
921 8 push @manual, $module;
922 }
923 else {
924 0 carp "$module has no import function";
925 }
926 }
927  
928 8 ▶ if (@manual) {
Branch: 1 branch
BranchTrueFalseTotal
if (@manual) 8 0 8
929 # load classes via string eval (yuk!)
930 8 $self->_set_eval($class, @manual);
931 }
932  
933 8 return $self;
934 }
935  
936 # cache code to eval to minimise string eval calls
937 8 ▶sub _set_eval {
Subroutine _set_eval: called CC=1 SCAR=0.0
938 8 my ($self, $class, @manual) = @_;
939  
940 my $code = join("\n",
941 "package $class;",
942 8 map {"use $_;"} @manual
943 );
944  
945 8 push @{$self->{__eval_cache}}, $code;
946 }
947  
948 # process pending eval code and reset
949 14 ▶sub _do_eval {
Subroutine _do_eval: called CC=3 SCAR=11.0
950 14 my $self = shift;
951  
952 14 my $cache = delete $self->{__eval_cache};
953  
954 14 ▶ if (defined $cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cache) 4 10 14
955 4 my $code = join("\n\n", @$cache);
956  
957 4 ▶ eval $code;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
958  
959 4 ▶ croak "Eval error!\nCode:\n$code\n\nMessage: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 3 4
960 }
961  
962 13 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 28 ▶sub view_to_class {
Subroutine view_to_class: called CC=3 SCAR=11.0
Pod documented
979 28 my($self, $view) = @_;
980  
981 28 ▶ if (defined $view and length $view) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $view and length $view) { } 26 2 28
Condition100%3/3
defined $view and length $view
!ll&&!rl&&r
1126
MC/DC100%2/2
defined $view and length $view
defined $view length $view
Truth table100%3/3
A and B
A= defined $viewB= length $view
ABresult
0X0
100
111
982 # cribbed from Class::DBI::Loader
983 26 $view = join('', map { ucfirst } split(/[\W_]+/, $view));
984  
985 26 return join('::', $self->get_namespace, $view);
986 }
987 else {
988 2 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 7 our @driver_methods = qw(
1094 base_class
1095 get_views
1096 get_view_cols
1097 );
1098  
1099 7 for my $method (@driver_methods) {
1100 7 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1101 6 ▶ *$method = sub { $_[0]->_refer_to_handler($method) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1102 }
1103  
1104 6 ▶sub _refer_to_handler {
Subroutine _refer_to_handler: called CC=2 SCAR=6.9
1105 6 my($self, $sub) = @_;
1106 6 my $handler = ref $self;
1107  
1108 6 ▶ if ($handler eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handler eq __PACKAGE__) { } 3 3 6
1109 # We haven't reblessed into a subclass
1110 3 confess "No handler loaded, try calling set_dsn() first";
1111 }
1112 else {
1113 3 confess "$sub not overridden by $handler";
1114 }
1115 }
1116  
1117 7 1;
1118  
1119 __END__
« ViewLoader/Auto.pm ↑ Summary