]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Utils/CStoreEditor.pm
Call set_audit_info and clear_audit_info DB funcs
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Utils / CStoreEditor.pm
1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Event;
8 use Data::Dumper;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
12 my %PERMS;
13 my $cache;
14 my %xact_ed_cache;
15
16 our $always_xact = 0;
17 our $_loaded = 1;
18
19 #my %PERMS = (
20 #       'biblio.record_entry'   => { update => 'UPDATE_MARC' },
21 #       'asset.copy'                            => { update => 'UPDATE_COPY'},
22 #       'asset.call_number'             => { update => 'UPDATE_VOLUME'},
23 #       'action.circulation'            => { retrieve => 'VIEW_CIRCULATIONS'},
24 #);
25
26 sub flush_forced_xacts {
27     for my $k ( keys %xact_ed_cache ) {
28         try {
29             $xact_ed_cache{$k}->rollback;
30         } catch Error with {
31             # rollback failed
32         };
33         delete $xact_ed_cache{$k};
34     }
35 }
36
37 # -----------------------------------------------------------------------------
38 # Export some useful functions
39 # -----------------------------------------------------------------------------
40 use vars qw(@EXPORT_OK %EXPORT_TAGS);
41 use Exporter;
42 use base qw/Exporter/;
43 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
44 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
45
46 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
47
48 sub new_rstore_editor { 
49         my $e = OpenILS::Utils::CStoreEditor->new(@_); 
50         $e->app('open-ils.reporter-store');
51         return $e;
52 }
53
54
55 # -----------------------------------------------------------------------------
56 # Log levels
57 # -----------------------------------------------------------------------------
58 use constant E => 'error';
59 use constant W => 'warn';
60 use constant I => 'info';
61 use constant D => 'debug';
62 use constant A => 'activity';
63
64
65
66 # -----------------------------------------------------------------------------
67 # Params include:
68 #       xact=><true> : creates a storage transaction
69 #       authtoken=>$token : the login session key
70 # -----------------------------------------------------------------------------
71 sub new {
72         my( $class, %params ) = @_;
73         $class = ref($class) || $class;
74         my $self = bless( \%params, $class );
75         $self->{checked_perms} = {};
76         return $self;
77 }
78
79 sub DESTROY {
80         my $self = shift;
81         $self->reset;
82         return undef;
83 }
84
85 sub app {
86         my( $self, $app ) = @_;
87         $self->{app} = $app if $app;
88         $self->{app} = 'open-ils.cstore' unless $self->{app};
89         return $self->{app};
90 }
91
92
93 # -----------------------------------------------------------------------------
94 # Log the editor metadata along with the log string
95 # -----------------------------------------------------------------------------
96 sub log {
97         my( $self, $lev, $str ) = @_;
98         my $s = "editor[";
99     if ($always_xact) {
100         $s .= "!|";
101     } elsif ($self->{xact}) {
102         $s .= "1|";
103     } else {
104             $s .= "0|";
105     }
106         $s .= "0" unless $self->requestor;
107         $s .= $self->requestor->id if $self->requestor;
108         $s .= "]";
109         $logger->$lev("$s $str");
110 }
111
112 # -----------------------------------------------------------------------------
113 # Verifies the auth token and fetches the requestor object
114 # -----------------------------------------------------------------------------
115 sub checkauth {
116         my $self = shift;
117         $self->log(D, "checking auth token ".$self->authtoken);
118
119         my $content = $U->simplereq( 
120                 'open-ils.auth', 
121                 'open-ils.auth.session.retrieve', $self->authtoken, 1);
122
123     if(!$content or $U->event_code($content)) {
124         $self->event( ($content) ? $content : OpenILS::Event->new('NO_SESSION'));
125         return undef;
126     }
127
128     $self->{authtime} = $content->{authtime};
129         return $self->{requestor} = $content->{userobj};
130 }
131
132 =head1 test
133
134 sub checkauth {
135         my $self = shift;
136         $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
137         $self->log(D, "checking cached auth token ".$self->authtoken);
138         my $user = $cache->get_cache("oils_auth_".$self->authtoken);
139         return $self->{requestor} = $user->{userobj} if $user;
140         $self->event(OpenILS::Event->new('NO_SESSION'));
141         return undef;
142 }
143
144 =cut
145
146
147 # -----------------------------------------------------------------------------
148 # Returns the last generated event
149 # -----------------------------------------------------------------------------
150 sub event {
151         my( $self, $evt ) = @_;
152         $self->{event} = $evt if $evt;
153         return $self->{event};
154 }
155
156 # -----------------------------------------------------------------------------
157 # Destroys the transaction and disconnects where necessary,
158 # then returns the last event that occurred
159 # -----------------------------------------------------------------------------
160 sub die_event {
161         my $self = shift;
162     my $evt = shift;
163         $self->rollback;
164     $self->died(1);
165     $self->event($evt);
166         return $self->event;
167 }
168
169
170 # -----------------------------------------------------------------------------
171 # Clears the last caught event
172 # -----------------------------------------------------------------------------
173 sub clear_event {
174         my $self = shift;
175         $self->{event} = undef;
176 }
177
178 sub died {
179     my($self, $died) = @_;
180     $self->{died} = $died if defined $died;
181     return $self->{died};
182 }
183
184 sub authtoken {
185         my( $self, $auth ) = @_;
186         $self->{authtoken} = $auth if $auth;
187         return $self->{authtoken};
188 }
189
190 sub authtime {
191         my( $self, $auth ) = @_;
192         $self->{authtime} = $auth if $auth;
193         return $self->{authtime};
194 }
195
196 sub timeout {
197     my($self, $to) = @_;
198     $self->{timeout} = $to if defined $to;
199     return defined($self->{timeout}) ? $self->{timeout} : 60;
200 }
201
202 # -----------------------------------------------------------------------------
203 # fetches the session, creating if necessary.  If 'xact' is true on this
204 # object, a db session is created
205 # -----------------------------------------------------------------------------
206 sub session {
207         my( $self, $session ) = @_;
208         $self->{session} = $session if $session;
209
210         if(!$self->{session}) {
211                 $self->{session} = OpenSRF::AppSession->create($self->app);
212
213                 if( ! $self->{session} ) {
214                         my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
215                         $self->log(E, $str);
216                         throw OpenSRF::EX::ERROR ($str);
217                 }
218
219                 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
220                 $self->xact_begin if $self->{xact} or $always_xact;
221         }
222
223     $xact_ed_cache{$self->{xact_id}} = $self if $always_xact and $self->{xact_id};
224         return $self->{session};
225 }
226
227
228 # -----------------------------------------------------------------------------
229 # Starts a storage transaction
230 # -----------------------------------------------------------------------------
231 sub xact_begin {
232     my $self = shift;
233     return $self->{xact_id} if $self->{xact_id};
234     $self->session->connect unless $self->session->state == OpenSRF::AppSession::CONNECTED();
235         $self->log(D, "starting new database transaction");
236         unless($self->{xact_id}) {
237             my $stat = $self->request($self->app . '.transaction.begin');
238             $self->log(E, "error starting database transaction") unless $stat;
239         $self->{xact_id} = $stat;
240         if($self->authtoken) {
241             if(!$self->requestor) {
242                 $self->checkauth;
243             }
244             my $user_id = undef;
245             my $ws_id = undef;
246             if($self->requestor) {
247                 $user_id = $self->requestor->id;
248                 $ws_id = $self->requestor->wsid;
249             }
250             $self->request($self->app . '.set_audit_info', $self->authtoken, $user_id, $ws_id);
251         }
252     }
253     $self->{xact} = 1;
254     return $self->{xact_id};
255 }
256
257 # -----------------------------------------------------------------------------
258 # Commits a storage transaction
259 # -----------------------------------------------------------------------------
260 sub xact_commit {
261         my $self = shift;
262     return unless $self->{xact_id};
263         $self->log(D, "comitting db session");
264         my $stat = $self->request($self->app.'.transaction.commit');
265         $self->log(E, "error comitting database transaction") unless $stat;
266     delete $self->{xact_id};
267     delete $self->{xact};
268         return $stat;
269 }
270
271 # -----------------------------------------------------------------------------
272 # Rolls back a storage stransaction
273 # -----------------------------------------------------------------------------
274 sub xact_rollback {
275         my $self = shift;
276     return unless $self->{session} and $self->{xact_id};
277         $self->log(I, "rolling back db session");
278         my $stat = $self->request($self->app.".transaction.rollback");
279         $self->log(E, "error rolling back database transaction") unless $stat;
280     delete $self->{xact_id};
281     delete $self->{xact};
282         return $stat;
283 }
284
285
286 # -----------------------------------------------------------------------------
287 # Savepoint functions.  If no savepoint name is provided, the same name is used 
288 # for each successive savepoint, in which case only the last savepoint set can 
289 # be released or rolled back.
290 # -----------------------------------------------------------------------------
291 sub set_savepoint {
292     my $self = shift;
293     my $name = shift || 'savepoint';
294     return unless $self->{session} and $self->{xact_id};
295         $self->log(I, "setting savepoint '$name'");
296         my $stat = $self->request($self->app.".savepoint.set", $name)
297             or $self->log(E, "error setting savepoint '$name'");
298     return $stat;
299 }
300
301 sub release_savepoint {
302     my $self = shift;
303     my $name = shift || 'savepoint';
304     return unless $self->{session} and $self->{xact_id};
305         $self->log(I, "releasing savepoint '$name'");
306         my $stat = $self->request($self->app.".savepoint.release", $name)
307         or $self->log(E, "error releasing savepoint '$name'");
308     return $stat;
309 }
310
311 sub rollback_savepoint {
312     my $self = shift;
313     my $name = shift || 'savepoint';
314     return unless $self->{session} and $self->{xact_id};
315         $self->log(I, "rollback savepoint '$name'");
316         my $stat = $self->request($self->app.".savepoint.rollback", $name)
317         or $self->log(E, "error rolling back savepoint '$name'");
318     return $stat;
319 }
320
321
322 # -----------------------------------------------------------------------------
323 # Rolls back the transaction and disconnects
324 # -----------------------------------------------------------------------------
325 sub rollback {
326         my $self = shift;
327     my $err;
328     my $ret;
329         try {
330         $self->xact_rollback;
331     } catch Error with  {
332         $err = shift
333     } finally {
334         $ret = $self->disconnect
335     };
336     throw $err if ($err);
337     return $ret;
338 }
339
340 sub disconnect {
341         my $self = shift;
342         $self->session->disconnect if 
343         $self->{session} and 
344         $self->{session}->state == OpenSRF::AppSession::CONNECTED();
345     delete $self->{session};
346 }
347
348
349 # -----------------------------------------------------------------------------
350 # commits the db session and destroys the session
351 # returns the status of the commit call
352 # -----------------------------------------------------------------------------
353 sub commit {
354         my $self = shift;
355         return unless $self->{xact_id};
356         my $stat = $self->xact_commit;
357     $self->disconnect;
358     return $stat;
359 }
360
361 # -----------------------------------------------------------------------------
362 # clears all object data. Does not commit the db transaction.
363 # -----------------------------------------------------------------------------
364 sub reset {
365         my $self = shift;
366         $self->disconnect;
367         $$self{$_} = undef for (keys %$self);
368 }
369
370
371 # -----------------------------------------------------------------------------
372 # commits and resets
373 # -----------------------------------------------------------------------------
374 sub finish {
375         my $self = shift;
376     my $err;
377     my $ret;
378         try {
379         $self->commit;
380     } catch Error with  {
381         $err = shift
382     } finally {
383         $ret = $self->reset
384     };
385     throw $err if ($err);
386     return $ret;
387 }
388
389
390
391 # -----------------------------------------------------------------------------
392 # Does a simple storage request
393 # -----------------------------------------------------------------------------
394 sub request {
395         my( $self, $method, @params ) = @_;
396
397     my $val;
398         my $err;
399         my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
400         my $locale = $self->session->session_locale;
401
402         $self->log(I, "request $locale $method $argstr");
403
404         if( ($self->{xact} or $always_xact) and 
405                         $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
406                 #$logger->error("CStoreEditor lost it's connection!!");
407                 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
408         }
409
410
411         try {
412
413         my $req = $self->session->request($method, @params);
414
415         if($self->substream) {
416             $self->log(D,"running in substream mode");
417             $val = [];
418             while( my $resp = $req->recv(timeout => $self->timeout) ) {
419                 push(@$val, $resp->content) if $resp->content and not $self->discard;
420             }
421
422         } else {
423             my $resp = $req->recv(timeout => $self->timeout);
424             if($req->failed) {
425                 $err = $resp;
426                         $self->log(E, "request error $method : $argstr : $err");
427             } else {
428                 $val = $resp->content if $resp;
429             }
430         }
431
432         $req->finish;
433
434         } catch Error with {
435                 $err = shift;
436                 $self->log(E, "request error $method : $argstr : $err");
437         };
438
439         throw $err if $err;
440         return $val;
441 }
442
443 sub substream {
444    my( $self, $bool ) = @_;
445    $self->{substream} = $bool if defined $bool;
446    return $self->{substream};
447 }
448
449 # -----------------------------------------------------------------------------
450 # discard response data instead of returning it to the caller.  currently only 
451 # works in conjunction with substream mode.  
452 # -----------------------------------------------------------------------------
453 sub discard {
454    my( $self, $bool ) = @_;
455    $self->{discard} = $bool if defined $bool;
456    return $self->{discard};
457 }
458
459
460 # -----------------------------------------------------------------------------
461 # Sets / Returns the requestor object.  This is set when checkauth succeeds.
462 # -----------------------------------------------------------------------------
463 sub requestor {
464         my($self, $requestor) = @_;
465         $self->{requestor} = $requestor if $requestor;
466         return $self->{requestor};
467 }
468
469
470
471 # -----------------------------------------------------------------------------
472 # Holds the last data received from a storage call
473 # -----------------------------------------------------------------------------
474 sub data {
475         my( $self, $data ) = @_;
476         $self->{data} = $data if defined $data;
477         return $self->{data};
478 }
479
480
481 # -----------------------------------------------------------------------------
482 # True if this perm has already been checked at this org
483 # -----------------------------------------------------------------------------
484 sub perm_checked {
485         my( $self, $perm, $org ) = @_;
486         $self->{checked_perms}->{$org} = {}
487                 unless $self->{checked_perms}->{$org};
488         my $checked = $self->{checked_perms}->{$org}->{$perm};
489         if(!$checked) {
490                 $self->{checked_perms}->{$org}->{$perm} = 1;
491                 return 0;
492         }
493         return 1;
494 }
495
496
497
498 # -----------------------------------------------------------------------------
499 # Returns true if the requested perm is allowed.  If the perm check fails,
500 # $e->event is set and undef is returned
501 # The perm user is $e->requestor->id and perm org defaults to the requestor's
502 # ws_ou
503 # if perm is an array of perms, method will return true at the first allowed
504 # permission.  If none of the perms are allowed, the perm_failure event
505 # is created with the last perm to fail
506 # -----------------------------------------------------------------------------
507 my $PERM_QUERY = {
508     select => {
509         au => [ {
510             transform => 'permission.usr_has_perm',
511             alias => 'has_perm',
512             column => 'id',
513             params => []
514         } ]
515     },
516     from => 'au',
517     where => {},
518 };
519
520 my $OBJECT_PERM_QUERY = {
521     select => {
522         au => [ {
523             transform => 'permission.usr_has_object_perm',
524             alias => 'has_perm',
525             column => 'id',
526             params => []
527         } ]
528     },
529     from => 'au',
530     where => {},
531 };
532
533 sub allowed {
534         my( $self, $perm, $org, $object, $hint ) = @_;
535         my $uid = $self->requestor->id;
536         $org ||= $self->requestor->ws_ou;
537
538     my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
539
540     for $perm (@$perms) {
541             $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
542     
543         if($object) {
544             my $params;
545             if(ref $object) {
546                 # determine the ID field and json_hint from the object
547                 my $id_field = $object->Identity;
548                 $params = [$perm, $object->json_hint, $object->$id_field];
549             } else {
550                 # we were passed an object-id and json_hint
551                 $params = [$perm, $hint, $object];
552             }
553             push(@$params, $org) if $org;
554             $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
555             $OBJECT_PERM_QUERY->{where}->{id} = $uid;
556             return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
557
558         } else {
559             $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
560             $PERM_QUERY->{where}->{id} = $uid;
561             return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
562         }
563     }
564
565     # set the perm failure event if the permission check returned false
566         my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
567         $self->event($e);
568         return undef;
569 }
570
571
572 # -----------------------------------------------------------------------------
573 # Returns the list of object IDs this user has object-specific permissions for
574 # -----------------------------------------------------------------------------
575 sub objects_allowed {
576     my($self, $perm, $obj_type) = @_;
577
578     my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
579     my @ids;
580
581     for $perm (@$perms) {
582         my $query = {
583             select => {puopm => ['object_id']},
584             from => {
585                 puopm => {
586                     ppl => {field => 'id',fkey => 'perm'}
587                 }
588             },
589             where => {
590                 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
591                 '+ppl' => {code => $perm}
592             }
593         };
594     
595         my $list = $self->json_query($query);
596         push(@ids, 0+$_->{object_id}) for @$list;
597     }
598
599    my %trim;
600    $trim{$_} = 1 for @ids;
601    return [ keys %trim ];
602 }
603
604
605 # -----------------------------------------------------------------------------
606 # checks the appropriate perm for the operation
607 # -----------------------------------------------------------------------------
608 sub _checkperm {
609         my( $self, $ptype, $action, $org ) = @_;
610         $org ||= $self->requestor->ws_ou;
611         my $perm = $PERMS{$ptype}{$action};
612         if( $perm ) {
613                 return undef if $self->perm_checked($perm, $org);
614                 return $self->event unless $self->allowed($perm, $org);
615         } else {
616                 $self->log(I, "no perm provided for $ptype.$action");
617         }
618         return undef;
619 }
620
621
622
623 # -----------------------------------------------------------------------------
624 # Logs update actions to the activity log
625 # -----------------------------------------------------------------------------
626 sub log_activity {
627         my( $self, $type, $action, $arg ) = @_;
628         my $str = "$type.$action";
629         $str .= _prop_string($arg);
630         $self->log(A, $str);
631 }
632
633
634
635 sub _prop_string {
636         my $obj = shift;
637         my @props = $obj->properties;
638         my $str = "";
639         for(@props) {
640                 my $prop = $obj->$_() || "";
641                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
642                 $str .= " $_=$prop";
643         }
644         return $str;
645 }
646
647
648 sub __arg_to_string {
649         my $arg = shift;
650         return "" unless defined $arg;
651         if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
652         my $idf = $arg->Identity;
653                 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
654         }
655         return OpenSRF::Utils::JSON->perl2JSON($arg);
656         return "";
657 }
658
659
660 # -----------------------------------------------------------------------------
661 # This does the actual storage query.
662 #
663 # 'search' calls become search_where calls and $arg can be a search hash or
664 # an array-ref of storage search options.  
665 #
666 # 'retrieve' expects an id
667 # 'update' expects an object
668 # 'create' expects an object
669 # 'delete' expects an object
670 #
671 # All methods return true on success and undef on failure.  On failure, 
672 # $e->event is set to the generated event.  
673 # Note: this method assumes that updating a non-changed object and 
674 # thereby receiving a 0 from storage, is a successful update.  
675 #
676 # The method will therefore return true so the caller can just do 
677 # $e->update_blah($x) or return $e->event;
678 # The true value returned from storage for all methods will be stored in 
679 # $e->data, until the next method is called.
680 #
681 # not-found events are generated on retrieve and serach methods.
682 # action=search methods will return [] (==true) if no data is found.  If the
683 # caller is interested in the not found event, they can do:  
684 # return $e->event unless @$results; 
685 # -----------------------------------------------------------------------------
686 sub runmethod {
687         my( $self, $action, $type, $arg, $options ) = @_;
688
689    $options ||= {};
690
691         if( $action eq 'retrieve' ) {
692                 if(! defined($arg) ) {
693                         $self->log(W,"$action $type called with no ID...");
694                         $self->event(_mk_not_found($type, $arg));
695                         return undef;
696                 } elsif( ref($arg) =~ /Fieldmapper/ ) {
697                         $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
698             my $idf = $arg->Identity;
699                         $arg = $arg->$idf;
700                 }
701         }
702
703         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
704         my $method = $self->app.".direct.$type.$action";
705
706         if( $action eq 'search' ) {
707                 $method .= '.atomic';
708
709         } elsif( $action eq 'batch_retrieve' ) {
710                 $action = 'search';
711                 $method =~ s/batch_retrieve/search/o;
712                 $method .= '.atomic';
713                 my $tt = $type;
714                 $tt =~ s/\./::/og;
715                 my $fmobj = "Fieldmapper::$tt";
716                 my $ident_field = $fmobj->Identity;
717
718                 if (ref $arg[0] eq 'ARRAY') {
719                         # $arg looks like: ([1, 2, 3], {search_args})
720                         @arg = ( { $ident_field => $arg[0] }, @arg[1 .. $#arg] );
721                 } else {
722                         # $arg looks like: [1, 2, 3]
723                         @arg = ( { $ident_field => $arg } );
724                 }
725
726         } elsif( $action eq 'retrieve_all' ) {
727                 $action = 'search';
728                 $method =~ s/retrieve_all/search/o;
729                 my $tt = $type;
730                 $tt =~ s/\./::/og;
731                 my $fmobj = "Fieldmapper::$tt";
732                 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
733                 $method .= '.atomic';
734         }
735
736         $method =~ s/search/id_list/o if $options->{idlist};
737
738     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
739     $self->timeout($$options{timeout});
740     $self->discard($$options{discard});
741
742         # remove any stale events
743         $self->clear_event;
744
745         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
746                 if(!($self->{xact} or $always_xact)) {
747                         $logger->error("Attempt to update DB while not in a transaction : $method");
748                         throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
749                 }
750                 $self->log_activity($type, $action, $arg);
751         }
752
753         if($$options{checkperm}) {
754                 my $a = ($action eq 'search') ? 'retrieve' : $action;
755                 my $e = $self->_checkperm($type, $a, $$options{permorg});
756                 if($e) {
757                         $self->event($e);
758                         return undef;
759                 }
760         }
761
762         my $obj; 
763         my $err = '';
764
765         try {
766                 $obj = $self->request($method, @arg);
767         } catch Error with { $err = shift; };
768         
769
770         if(!defined $obj) {
771                 $self->log(I, "request returned no data : $method");
772
773                 if( $action eq 'retrieve' ) {
774                         $self->event(_mk_not_found($type, $arg));
775
776                 } elsif( $action eq 'update' or 
777                                 $action eq 'delete' or $action eq 'create' ) {
778                         my $evt = OpenILS::Event->new(
779                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
780                         $self->event($evt);
781                 }
782
783                 if( $err ) {
784                         $self->event( 
785                                 OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
786                                         payload => $arg, debug => "$err" ));
787                         return undef;
788                 }
789
790                 return undef;
791         }
792
793         if( $action eq 'create' and $obj == 0 ) {
794                 my $evt = OpenILS::Event->new(
795                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
796                 $self->event($evt);
797                 return undef;
798         }
799
800         # If we havn't dealt with the error in a nice way, go ahead and throw it
801         if( $err ) {
802                 $self->event( 
803                         OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
804                                 payload => $arg, debug => "$err" ));
805                 return undef;
806         }
807
808         if( $action eq 'search' ) {
809                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
810                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
811         }
812
813         if( $action eq 'create' ) {
814         my $idf = $obj->Identity;
815                 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
816                 $arg->$idf($obj->$idf);
817         }
818
819         $self->data($obj); # cache the data for convenience
820
821         return ($obj) ? $obj : 1;
822 }
823
824
825 sub _mk_not_found {
826         my( $type, $arg ) = @_;
827         (my $t = $type) =~ s/\./_/og;
828         $t = uc($t);
829         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
830 }
831
832
833
834 # utility method for loading
835 sub __fm2meth { 
836         my $str = shift;
837         my $sep = shift;
838         $str =~ s/Fieldmapper:://o;
839         $str =~ s/::/$sep/g;
840         return $str;
841 }
842
843
844 # -------------------------------------------------------------
845 # Load up the methods from the FM classes
846 # -------------------------------------------------------------
847
848 sub init {
849     no warnings;    #  Here we potentially redefine subs via eval
850     my $map = $Fieldmapper::fieldmap;
851     for my $object (keys %$map) {
852         my $obj  = __fm2meth($object, '_');
853         my $type = __fm2meth($object, '.');
854         foreach my $command (qw/ update retrieve search create delete batch_retrieve retrieve_all /) {
855             eval "sub ${command}_$obj {return shift()->runmethod('$command', '$type', \@_);}\n";
856         }
857         # TODO: performance test against concatenating a big string of all the subs and eval'ing only ONCE.
858     }
859 }
860
861 init();  # Add very many subs to this namespace
862
863 sub json_query {
864     my( $self, $arg, $options ) = @_;
865     $options ||= {};
866         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
867     my $method = $self->app.'.json_query.atomic';
868     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
869
870     $self->timeout($$options{timeout});
871     $self->discard($$options{discard});
872         $self->clear_event;
873     my $obj;
874     my $err;
875     
876     try {
877         $obj = $self->request($method, @arg);
878     } catch Error with { $err = shift; };
879
880     if( $err ) {
881         $self->event(
882             OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
883             payload => $arg, debug => "$err" ));
884         return undef;
885     }
886
887     $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));
888     return $obj;
889 }
890
891
892
893 1;
894
895