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