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