blib/lib/PGObject/Simple.pm

filter: Statementstmt 46.5% 47 / 101 Branchbran 3.8% 1 / 26 Conditioncond 5.7% 2 / 35 MC/DCmcdc 4.3% 1 / 23 Subroutinesub 77.7% 14 / 18 Podpod 100% 6 / 6 totaltotal 33.9% 71 / 209 CC 27 SCAR 43.3
CC
27
Cov
31%
_arg_defaults
210.0
_self_to_arg
42.0
call_dbmethod
20.0
CRAP 75.8
↑ Summary
1 package PGObject::Simple;
2  
3 4 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use parent 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 4 ▶use Carp::Clan qr/^PGObject\b/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use PGObject;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 =head1 NAME
15  
16 PGObject::Simple - Minimalist stored procedure mapper based on LedgerSMB's DBObject
17  
18 =head1 VERSION
19  
20 Version 3.1.0
21  
22 =cut
23  
24 4 our $VERSION = '3.1.0';
25  
26 =head1 SYNOPSIS
27  
28 use PGObject::Simple;
29 my $obj = PGObject::Simple->new(%myhash);
30 $obj->set_dbh($dbh); # Database connection
31  
32 To call a stored procedure with enumerated arguments.
33  
34 my @results = $obj->call_procedure(
35 funcname => $funcname,
36 funcschema => $funcschema,
37 args => [$arg1, $arg2, $arg3],
38 );
39  
40 You can add something like a running total as well:
41  
42 my @results = $obj->call_procedure(
43 funcname => $funcname,
44 funcschema => $funcschema,
45 args => [$arg1, $arg2, $arg3],
46 running_funcs => [{agg => 'sum(amount)', alias => 'total'}],
47 );
48  
49 To call a stored procedure with named arguments from a hashref. This is
50 typically done when mapping object properties in to stored procedure arguments.
51  
52 my @results = $obj->call_dbmethod(
53 funcname => $funcname,
54 funcschema => $funcschema,
55 running_funcs => [{agg => 'sum(amount)', alias => 'total'}],
56 );
57  
58 To call a stored procedure with named arguments from a hashref with overrides.
59  
60 my @results = $obj->call_dbmethod(
61 funcname => 'customer_save',
62 funcschema => 'public',
63 running_funcs => [{agg => 'sum(amount)', alias => 'total'}],
64 args => { id => undef }, # force to create new!
65 );
66  
67  
68 =head1 EXPORTS
69  
70 We now allow various calls to be exported. We recommend using the tags.
71  
72 =head2 One-at-a-time Exports
73  
74 =over
75  
76 =item call_dbmethod
77  
78 =item call_procedure
79  
80 =item set_dbh
81  
82 =item _set_funcprefix
83  
84 =item _set_funcschema
85  
86 =item _set_registry
87  
88 =back
89  
90 =head2 Export Tags
91  
92 Below are the export tags listed including the leading ':' used to invoke them.
93  
94 =over
95  
96 =item :mapper
97 call_dbmethod, call_procedure, and set_dbh
98  
99 =item :full
100 All methods that can be exported at once.
101  
102 =back
103  
104 =cut
105  
106 4 our @EXPORT_OK = qw(call_dbmethod call_procedure set_dbh associate dbh
107 _set_funcprefix
108 _set_funcschema _set_registry);
109  
110 4 our %EXPORT_TAGS = (mapper => [qw(call_dbmethod call_procedure set_dbh dbh)],
111 full => \@EXPORT_OK);
112  
113 =head1 DESCRIPTION
114  
115 PGObject::Simple a top-half object system for PGObject which is simple and
116 inspired by (and a subset functionally speaking of) the simple stored procedure
117 object method system of LedgerSMB 1.3. The framework discovers stored procedure
118 APIs and dispatches to them and can therefore be a base for application-specific
119 object models and much more.
120  
121 PGObject::Simple is designed to be light-weight and yet robust glue between your
122 object model and the RDBMS's stored procedures. It works by looking up the
123 stored procedure arguments, stripping them of the conventional prefix 'in_', and
124 mapping what is left to object property names. Properties can be
125 overridden by passing in a hashrefs in the args named argument. Named arguments
126 there will be used in place of object properties.
127  
128 This system is quite flexible, perhaps too much so, and it relies on the
129 database encapsulating its own logic behind self-documenting stored procedures
130 using consistent conventions. No function which is expected to be discovered can
131 be overloaded, and all arguments must be named for their object properties. For
132 this reason the use of this module fundamentally changes the contract of the
133 stored procedure from that of a fixed number of arguments in fixed types
134 contract to one where the name must be unique and the stored procedures must be
135 coded to the application's interface. This inverts the way we typically think
136 about stored procedures and makes them much more application friendly.
137  
138 =head1 SUBROUTINES/METHODS
139  
140 =head2 new
141  
142 This constructs a new object. Basically it copies the incoming hash (one level
143 deep) and then blesses it. If the hash passed in has a dbh member, the dbh
144 is set to that. This does not set the function prefix, as this is assumed to
145 be done implicitly by subclasses.
146  
147 =cut
148  
149 2 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
Pod documented
150 2 my ($self) = shift @_;
151 2 my %args = @_;
152 2 my $ref = {};
153 2 $ref->{$_} = $args{$_} for keys %args;
154 2 bless ($ref, $self);
155 2 $ref->set_dbh($ref->{dbh});
156 2 $ref->_set_funcprefix($ref->{_funcprefix});
157 2 $ref->_set_funcschema($ref->{_funcschema});
158 2 $ref->_set_registry($ref->{_registry});
159 2 ▶ $ref->associate($self) if ref $self;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 0 2 2
160 2 return $ref;
161 }
162  
163 =head2 set_dbh($dbh)
164  
165 Sets the database handle (needs DBD::Pg 2.0 or later) to $dbh
166  
167 =cut
168  
169 4 ▶sub set_dbh {
Subroutine set_dbh: called CC=1 SCAR=0.0
Pod documented
170 4 my ($self, $dbh) = @_;
171 4 $self->{_dbh} = $dbh;
172 }
173  
174 =head2 dbh
175  
176 Returns the database handle for the object.
177  
178 =cut
179  
180 4 ▶sub dbh {
Subroutine dbh: called CC=2 SCAR=7.1
Pod documented
181 4 my ($self) = @_;
182 4 ▶ return ($self->{_dbh} or $self->{_DBH});
Condition66%2/3
$self->{'_dbh'} || $self->{'_DBH'}
l!l&&r!l&&!r
301
MC/DC50%1/2
$self->{'_dbh'} || $self->{'_DBH'}
$self->{'_dbh'} $self->{'_DBH'}
Truth table66%2/3
A || B
A= $self->{'_dbh'}B= $self->{'_DBH'}
ABresult
1X1
011
000
183 }
184  
185 =head2 associate($pgobject)
186  
187 Sets the db handle to that from the $pgobject.
188  
189 =cut
190  
191 1 ▶sub associate {
Subroutine associate: called CC=1 SCAR=0.0
Pod documented
192 1 my ($self, $other) = @_;
193 1 $self->set_dbh($other->dbh);
194 }
195  
196 =head2 _set_funcprefix
197  
198 This sets the default funcprefix for future calls. The funcprefix can still be
199 overridden by passing in an explicit '' in a call. This is used to "claim" a
200 certain set of stored procedures in the database for use by an object.
201  
202 It is semi-private, intended to be called by subclasses directly, perhaps in
203 constructors, but not from outside the object.
204  
205 =cut
206  
207 2 ▶sub _set_funcprefix {
Subroutine _set_funcprefix: called CC=1 SCAR=0.0
208 2 my ($self, $funcprefix) = @_;
209 2 $self->{_func_prefix} = $funcprefix;
210 }
211  
212 =head2 _set_funcschema
213  
214 This sets the default funcschema for future calls. This is overwridden by
215 per-call arguments, (PGObject::Util::DBMethod provides for such overrides on a
216 per-method basis).
217  
218 =cut
219  
220 2 ▶sub _set_funcschema {
Subroutine _set_funcschema: called CC=1 SCAR=0.0
221 2 my ($self, $funcschema) = @_;
222 2 $self->{_func_schema} = $funcschema;
223 }
224  
225 =head2 _set_registry
226  
227 This sets the registry for future calls. The idea here is that this allows for
228 application object model wrappers to set which registry they are using, both for
229 predictability and ensuring that interoperability is possible.
230  
231 =cut
232  
233 2 ▶sub _set_registry {
Subroutine _set_registry: called CC=1 SCAR=0.0
234 2 my ($self, $registry) = @_;
235 2 $self->{_registry} = $registry;
236 }
237  
238 =head2 call_dbmethod
239  
240 Does a straight-forward mapping (as described below) to the stored procedure
241 arguments. Stored procedure arguments are looked up, a leading 'in_' is
242 stripped off where it exists, and the remaining string mapped back to an
243 object property. The $args{args} hashref can be used to override arguments by
244 name. Unknown properties are handled simply by passing a NULL in, so the
245 stored procedures should be prepared to handle these.
246  
247 As with call_procedure below, this returns a single hashref when called in a
248 scalar context, and a list of hashrefs when called in a list context.
249  
250 NEW IN 2.0: We now give preference to functions of the same name over
251 properties. So $obj->foo() will be used before $obj->{foo}. This enables
252 better data encapsulation.
253  
254 =cut
255  
256 0 ▶sub _arg_defaults {
Subroutine _arg_defaults: not called CC=14 SCAR=53.5
257 0 my ($self, %args) = @_;
258 0 local $@;
259 0 ▶ if (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) { } 0 0 0
260 0 ▶ $args{dbh} ||= eval { $self->dbh } ;
Condition0%0/3
$args{"dbh"} ||= eval { do { $self->dbh } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"dbh"} ||= eval { do { $self->dbh } }
$args{"dbh"} eval { do { $self->dbh } }
Truth table0%0/3
A ||= B
A= $args{"dbh"}B= eval { do { $self->dbh } }
ABresult
1X1
011
000
261 0 ▶ $args{funcprefix} //= eval { $self->funcprefix } ;
Condition0%0/3
$args{"funcprefix"} //= eval { do { $self->funcprefix } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcprefix"} //= eval { do { $self->funcprefix } }
$args{"funcprefix"} eval { do { $self->funcprefix } }
Truth table0%0/3
A //= B
A= $args{"funcprefix"}B= eval { do { $self->funcprefix } }
ABresult
1X1
011
000
262 0 ▶ $args{funcschema} //= eval { $self->funcschema } ;
Condition0%0/3
$args{"funcschema"} //= eval { do { $self->funcschema } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcschema"} //= eval { do { $self->funcschema } }
$args{"funcschema"} eval { do { $self->funcschema } }
Truth table0%0/3
A //= B
A= $args{"funcschema"}B= eval { do { $self->funcschema } }
ABresult
1X1
011
000
263 0 ▶ $args{funcprefix} //= $self->{_func_prefix};
Condition0%0/3
$args{"funcprefix"} //= $self->{"_func_prefix"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcprefix"} //= $self->{"_func_prefix"}
$args{"funcprefix"} $self->{"_func_prefix"}
Truth table0%0/3
A //= B
A= $args{"funcprefix"}B= $self->{"_func_prefix"}
ABresult
1X1
011
000
264 0 ▶ $args{funcschema} //= $self->{_func_schema};
Condition0%0/3
$args{"funcschema"} //= $self->{"_func_schema"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcschema"} //= $self->{"_func_schema"}
$args{"funcschema"} $self->{"_func_schema"}
Truth table0%0/3
A //= B
A= $args{"funcschema"}B= $self->{"_func_schema"}
ABresult
1X1
011
000
265 0 ▶ $args{funcprefix} //= eval {$self->_get_prefix() };
Condition0%0/3
$args{"funcprefix"} //= eval { do { $self->_get_prefix } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcprefix"} //= eval { do { $self->_get_prefix } }
$args{"funcprefix"} eval { do { $self->_get_prefix } }
Truth table0%0/3
A //= B
A= $args{"funcprefix"}B= eval { do { $self->_get_prefix } }
ABresult
1X1
011
000
266 } else {
267 # see if we have package-level reader/factories
268 0 ▶ $args{dbh} ||= "$self"->dbh; # if eval {"$self"->dbh};
Condition0%0/3
$args{"dbh"} ||= "$self"->dbh
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"dbh"} ||= "$self"->dbh
$args{"dbh"} "$self"->dbh
Truth table0%0/3
A ||= B
A= $args{"dbh"}B= "$self"->dbh
ABresult
1X1
011
000
269 0 ▶ $args{funcschema} //= "$self"->funcschema if eval {"$self"->funcschema};
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { "$self"->funcschema } } 0 0 0
Condition0%0/3
$args{"funcschema"} //= "$self"->funcschema
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcschema"} //= "$self"->funcschema
$args{"funcschema"} "$self"->funcschema
Truth table0%0/3
A //= B
A= $args{"funcschema"}B= "$self"->funcschema
ABresult
1X1
011
000
270 0 ▶ $args{funcprefix} //= "$self"->funcprefix if eval {"$self"->funcprefix};
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { "$self"->funcprefix } } 0 0 0
Condition0%0/3
$args{"funcprefix"} //= "$self"->funcprefix
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"funcprefix"} //= "$self"->funcprefix
$args{"funcprefix"} "$self"->funcprefix
Truth table0%0/3
A //= B
A= $args{"funcprefix"}B= "$self"->funcprefix
ABresult
1X1
011
000
271 }
272 0 ▶ $args{funcprefix} //= '';
Condition0%0/2
$args{"funcprefix"} //= ""
l!l
00
MC/DC0%0/1
$args{"funcprefix"} //= ""
$args{"funcprefix"}
Truth table0%0/2
A
A= $args{"funcprefix"}
Aresult
11
00
273  
274 0 return %args
275 }
276  
277 0 ▶sub _self_to_arg { # refactored from map call, purely internal
Subroutine _self_to_arg: not called CC=6 SCAR=37.4
278 0 my ($self, $args, $argname) = @_;
279 0 my $db_arg;
280 0 $argname =~ s/^in_//;
281 0 local $@;
282 0 ▶ if (ref $self and $argname){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self and $argname) 0 0 0
Condition0%0/3
ref $self and $argname
!ll&&!rl&&r
000
MC/DC0%0/2
ref $self and $argname
ref $self $argname
Truth table0%0/3
A and B
A= ref $selfB= $argname
ABresult
0X0
100
111
283 0 ▶ if (eval { $self->can($argname) } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $self->can($argname) } }) { } 0 0 0
284 0 eval { $db_arg = $self->can($argname)->($self) };
285 } else {
286 0 $db_arg = $self->{$argname};
287 }
288 }
289 0 ▶ $db_arg = $args->{args}->{$argname} if exists $args->{args}->{$argname};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"args"}{$argname} 0 0 0
290 0 ▶ $db_arg = $db_arg->to_db if eval {$db_arg->can('to_db')};
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $db_arg->can("to_db") } } 0 0 0
291  
292 0 return $db_arg;
293 }
294  
295 0 ▶sub call_dbmethod {
Subroutine call_dbmethod: not called CC=4 SCAR=30.0
Pod documented
296 0 my ($self) = shift @_;
297 0 my %args = @_;
298 croak $log->error( 'No function name provided' )
299 0 ▶ unless $args{funcname};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"funcname"} 0 0 0
300 0 %args = _arg_defaults($self, %args);
301 croak $log->error( 'No DB handle provided' )
302 0 ▶ unless $args{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"dbh"} 0 0 0
303 0 my $info = PGObject->function_info(%args);
304  
305 0 my $arglist = [];
306 0 @{$arglist} = map { _self_to_arg($self, \%args, $_->{name}) }
307 0 @{$info->{args}};
308 0 $args{args} = $arglist;
309  
310 # The conditional return is necessary since the object may carry a registry
311 # --CT
312 0 ▶ return $self->call_procedure(%args) if ref $self;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 0 0 0
313 0 return __PACKAGE__->call_procedure(%args);
314 }
315  
316 =head2 call_procedure
317  
318 This is a lightweight wrapper around PGObject->call_procedure which merely
319 passes the currently attached db connection in. We use the previously set
320 funcprefix and dbh by default but other values can be passed in to override the
321 default object's values.
322  
323 This returns a single hashref when called in a scalar context, and a list of
324 hashrefs when called in a list context. When called in a scalar context it
325 simply returns the single first row returned.
326  
327 =cut
328  
329 0 ▶sub call_procedure {
Subroutine call_procedure: not called CC=3 SCAR=24.8
Pod documented
330 0 my ($self, %args) = @_;
331 0 %args = _arg_defaults($self, %args);
332 croak $log->error( 'No DB handle provided' )
333 0 ▶ unless $args{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"dbh"} 0 0 0
334 0 my @rows = PGObject->call_procedure(%args);
335 0 ▶ return shift @rows unless wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 0 0 0
336 0 return @rows;
337 }
338  
339 =head1 WRITING CLASSES WITH PGObject::Simple
340  
341 Unlike PGObject, which is only loosely tied to the functionality in question
342 and presumes that relevant information will be passed over a functional
343 interface, PGObject::Simple is a specific framework for object-oriented coding
344 in Perl. It can therefore be used alone or with other modules to provide quite
345 a bit of functionality.
346  
347 A PGObject::Simple object is a blessed hashref with no gettors or setters. This
348 is thus ideal for cases where you are starting and just need some quick mappings
349 of stored procedures to hashrefs. You reference properties simply with the
350 $object->{property} syntax. There is very little encapsulation in objects, and
351 very little abstraction except when it comes to the actual stored procedure
352 interfaces. In essence, PGObject::Simple generally assumes that the actual
353 data structure is essentially a public interface between the database and
354 whatever else is going on with the application.
355  
356 The general methods can then wrap call_procedure and call_dbmethod calls,
357 mapping out to stored procedures in the database.
358  
359 Stored procedures must be written to relatively exacting specifications.
360 Arguments must be named, with names prefixed optionally with 'in_' (if the
361 property name starts with 'in_' properly one must also prefix it).
362  
363 An example of a simple stored procedure might be:
364  
365 CREATE OR REPLACE FUNCTION customer_get(in_id int)
366 RETURNS setof customer language sql as $$
367  
368 select * from customer where id = $1;
369  
370 $$;
371  
372 This stored procedure could then be called with any of:
373  
374 $obj->call_dbmethod(
375 funcname => 'customer_get',
376 ); # retrieve the customer with the $obj->{id} id
377  
378 $obj->call_dbmethod(
379 funcname => 'customer_get',
380 args => {id => 3 },
381 ); # retrieve the customer with the id of 3 regardless of $obj->{id}
382  
383 $obj->call_procedure(
384 funcname => 'customer_get',
385 args => [3],
386 );
387  
388 =head1 AUTHOR
389  
390 Chris Travers, C<< <chris.travers at gmail.com> >>
391  
392 =head1 BUGS
393  
394 Please report any bugs or feature requests to C<bug-pgobject-simple at rt.cpan.org>, or through
395 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=PGObject-Simple>. I will be notified, and then you'll
396 automatically be notified of progress on your bug as I make changes.
397  
398  
399  
400  
401 =head1 SUPPORT
402  
403 You can find documentation for this module with the perldoc command.
404  
405 perldoc PGObject::Simple
406  
407  
408 You can also look for information at:
409  
410 =over 4
411  
412 =item * RT: CPAN's request tracker (report bugs here)
413  
414 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=PGObject-Simple>
415  
416 =item * MetaCPAN
417  
418 L<https://metacpan.org/dist/PGObject-Simple>
419  
420 =back
421  
422  
423 =head1 ACKNOWLEDGEMENTS
424  
425  
426 =head1 LICENSE AND COPYRIGHT
427  
428 COPYRIGHT (C) 2013-2014 Chris Travers
429 COPYRIGHT (C) 2014-2021 The LedgerSMB Core Team
430  
431 Redistribution and use in source and compiled forms with or without
432 modification, are permitted provided that the following conditions are met:
433  
434 =over
435  
436 =item
437  
438 Redistributions of source code must retain the above
439 copyright notice, this list of conditions and the following disclaimer as the
440 first lines of this file unmodified.
441  
442 =item
443  
444 Redistributions in compiled form must reproduce the above copyright
445 notice, this list of conditions and the following disclaimer in the
446 source code, documentation, and/or other materials provided with the
447 distribution.
448  
449 =back
450  
451 THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) "AS IS" AND
452 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
453 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
454 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR
455 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
456 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
457 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
458 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
459 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
460 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
461  
462 =cut
463  
464 4 1; # End of PGObject::Simple
↑ Summary