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