File Coverage

blib/lib/PGObject/Simple.pm
Criterion Covered Total %
statement 43 97 44.3
branch 1 26 3.8
condition 2 35 5.7
subroutine 14 18 77.7
pod 6 6 100.0
total 66 182 36.2


line stmt bran cond sub pod time code
1             package PGObject::Simple;
2              
3 3     3   69906 use 5.010;
  3         21  
4 3     3   17 use strict;
  3         5  
  3         87  
5 3     3   18 use warnings;
  3         5  
  3         105  
6 3     3   915 use parent 'Exporter';
  3         682  
  3         17  
7              
8 3     3   1684 use Carp::Clan qr/^PGObject\b/;
  3         12269  
  3         29  
9 3     3   1668 use Log::Any qw($log);
  3         25675  
  3         14  
10              
11 3     3   8067 use PGObject;
  3         72223  
  3         25  
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             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             our @EXPORT_OK = qw(call_dbmethod call_procedure set_dbh associate dbh
107             _set_funcprefix
108             _set_funcschema _set_registry);
109              
110             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             sub new {
150 2     2 1 104 my ($self) = shift @_;
151 2         7 my %args = @_;
152 2         5 my $ref = {};
153 2         12 $ref->{$_} = $args{$_} for keys %args;
154 2         6 bless ($ref, $self);
155 2         16 $ref->set_dbh($ref->{dbh});
156 2         10 $ref->_set_funcprefix($ref->{_funcprefix});
157 2         10 $ref->_set_funcschema($ref->{_funcschema});
158 2         7 $ref->_set_registry($ref->{_registry});
159 2 50       6 $ref->associate($self) if ref $self;
160 2         7 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             sub set_dbh {
170 4     4 1 535 my ($self, $dbh) = @_;
171 4         16 $self->{_dbh} = $dbh;
172             }
173              
174             =head2 dbh
175              
176             Returns the database handle for the object.
177              
178             =cut
179              
180             sub dbh {
181 4     4 1 11 my ($self) = @_;
182 4   66     21 return ($self->{_dbh} or $self->{_DBH});
183             }
184              
185             =head2 associate($pgobject)
186              
187             Sets the db handle to that from the $pgobject.
188              
189             =cut
190              
191             sub associate {
192 1     1 1 3 my ($self, $other) = @_;
193 1         4 $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             sub _set_funcprefix {
208 2     2   6 my ($self, $funcprefix) = @_;
209 2         4 $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             sub _set_funcschema {
221 2     2   17 my ($self, $funcschema) = @_;
222 2         4 $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             sub _set_registry {
234 2     2   6 my ($self, $registry) = @_;
235 2         6 $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             sub _arg_defaults {
257 0     0     my ($self, %args) = @_;
258 0           local $@;
259 0 0         if (ref $self) {
260 0   0       $args{dbh} ||= eval { $self->dbh } ;
  0            
261 0   0       $args{funcprefix} //= eval { $self->funcprefix } ;
  0            
262 0   0       $args{funcschema} //= eval { $self->funcschema } ;
  0            
263 0   0       $args{funcprefix} //= $self->{_func_prefix};
264 0   0       $args{funcschema} //= $self->{_func_schema};
265 0   0       $args{funcprefix} //= eval {$self->_get_prefix() };
  0            
266             } else {
267             # see if we have package-level reader/factories
268 0   0       $args{dbh} ||= "$self"->dbh; # if eval {"$self"->dbh};
269 0 0 0       $args{funcschema} //= "$self"->funcschema if eval {"$self"->funcschema};
  0            
270 0 0 0       $args{funcprefix} //= "$self"->funcprefix if eval {"$self"->funcprefix};
  0            
271             }
272 0   0       $args{funcprefix} //= '';
273              
274 0           return %args
275             }
276              
277             sub _self_to_arg { # refactored from map call, purely internal
278 0     0     my ($self, $args, $argname) = @_;
279 0           my $db_arg;
280 0           $argname =~ s/^in_//;
281 0           local $@;
282 0 0 0       if (ref $self and $argname){
283 0 0         if (eval { $self->can($argname) } ) {
  0            
284 0           eval { $db_arg = $self->can($argname)->($self) };
  0            
285             } else {
286 0           $db_arg = $self->{$argname};
287             }
288             }
289 0 0         $db_arg = $args->{args}->{$argname} if exists $args->{args}->{$argname};
290 0 0         $db_arg = $db_arg->to_db if eval {$db_arg->can('to_db')};
  0            
291              
292 0           return $db_arg;
293             }
294              
295             sub call_dbmethod {
296 0     0 1   my ($self) = shift @_;
297 0           my %args = @_;
298             croak $log->error( 'No function name provided' )
299 0 0         unless $args{funcname};
300 0           %args = _arg_defaults($self, %args);
301             croak $log->error( 'No DB handle provided' )
302 0 0         unless $args{dbh};
303 0           my $info = PGObject->function_info(%args);
304              
305 0           my $arglist = [];
306 0           @{$arglist} = map { _self_to_arg($self, \%args, $_->{name}) }
  0            
307 0           @{$info->{args}};
  0            
308 0           $args{args} = $arglist;
309              
310             # The conditional return is necessary since the object may carry a registry
311             # --CT
312 0 0         return $self->call_procedure(%args) if ref $self;
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             sub call_procedure {
330 0     0 1   my ($self, %args) = @_;
331 0           %args = _arg_defaults($self, %args);
332             croak $log->error( 'No DB handle provided' )
333 0 0         unless $args{dbh};
334 0           my @rows = PGObject->call_procedure(%args);
335 0 0         return shift @rows unless wantarray;
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<< >>
391              
392             =head1 BUGS
393              
394             Please report any bugs or feature requests to C, or through
395             the web interface at L. 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
415              
416             =item * MetaCPAN
417              
418             L
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             1; # End of PGObject::Simple