]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/CStoreEditor.pm
capture the timeout argument to json_query
[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")
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")
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")
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 # -----------------------------------------------------------------------------
306 sub commit {
307         my $self = shift;
308         return unless $self->{xact_id};
309         $self->xact_commit;
310         $self->session->disconnect;
311         $self->{session} = undef;
312 }
313
314 # -----------------------------------------------------------------------------
315 # clears all object data. Does not commit the db transaction.
316 # -----------------------------------------------------------------------------
317 sub reset {
318         my $self = shift;
319         $self->disconnect;
320         $$self{$_} = undef for (keys %$self);
321 }
322
323
324 # -----------------------------------------------------------------------------
325 # commits and resets
326 # -----------------------------------------------------------------------------
327 sub finish {
328         my $self = shift;
329         $self->commit;
330         $self->reset;
331 }
332
333
334
335 # -----------------------------------------------------------------------------
336 # Does a simple storage request
337 # -----------------------------------------------------------------------------
338 sub request {
339         my( $self, $method, @params ) = @_;
340
341     my $val;
342         my $err;
343         my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
344         my $locale = $self->session->session_locale;
345
346         $self->log(I, "request $locale $method $argstr");
347
348         if( ($self->{xact} or $always_xact) and 
349                         $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
350                 #$logger->error("CStoreEditor lost it's connection!!");
351                 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
352         }
353
354
355         try {
356
357         my $req = $self->session->request($method, @params);
358
359         if($self->substream) {
360             $self->log(D,"running in substream mode");
361             $val = [];
362             while( my $resp = $req->recv(timeout => $self->timeout) ) {
363                 push(@$val, $resp->content) if $resp->content;
364             }
365
366         } else {
367             my $resp = $req->recv(timeout => $self->timeout);
368             if($req->failed) {
369                 $err = $resp;
370                         $self->log(E, "request error $method : $argstr : $err");
371             } else {
372                 $val = $resp->content;
373             }
374         }
375
376         $req->finish;
377
378         } catch Error with {
379                 $err = shift;
380                 $self->log(E, "request error $method : $argstr : $err");
381         };
382
383         throw $err if $err;
384         return $val;
385 }
386
387 sub substream {
388    my( $self, $bool ) = @_;
389    $self->{substream} = $bool if defined $bool;
390    return $self->{substream};
391 }
392
393
394 # -----------------------------------------------------------------------------
395 # Sets / Returns the requestor object.  This is set when checkauth succeeds.
396 # -----------------------------------------------------------------------------
397 sub requestor {
398         my($self, $requestor) = @_;
399         $self->{requestor} = $requestor if $requestor;
400         return $self->{requestor};
401 }
402
403
404
405 # -----------------------------------------------------------------------------
406 # Holds the last data received from a storage call
407 # -----------------------------------------------------------------------------
408 sub data {
409         my( $self, $data ) = @_;
410         $self->{data} = $data if defined $data;
411         return $self->{data};
412 }
413
414
415 # -----------------------------------------------------------------------------
416 # True if this perm has already been checked at this org
417 # -----------------------------------------------------------------------------
418 sub perm_checked {
419         my( $self, $perm, $org ) = @_;
420         $self->{checked_perms}->{$org} = {}
421                 unless $self->{checked_perms}->{$org};
422         my $checked = $self->{checked_perms}->{$org}->{$perm};
423         if(!$checked) {
424                 $self->{checked_perms}->{$org}->{$perm} = 1;
425                 return 0;
426         }
427         return 1;
428 }
429
430
431
432 # -----------------------------------------------------------------------------
433 # Returns true if the requested perm is allowed.  If the perm check fails,
434 # $e->event is set and undef is returned
435 # The perm user is $e->requestor->id and perm org defaults to the requestor's
436 # ws_ou
437 # if perm is an array of perms, method will return true at the first allowed
438 # permission.  If none of the perms are allowed, the perm_failure event
439 # is created with the last perm to fail
440 # -----------------------------------------------------------------------------
441 my $PERM_QUERY = {
442     select => {
443         au => [ {
444             transform => 'permission.usr_has_perm',
445             alias => 'has_perm',
446             column => 'id',
447             params => []
448         } ]
449     },
450     from => 'au',
451     where => {},
452 };
453
454 my $OBJECT_PERM_QUERY = {
455     select => {
456         au => [ {
457             transform => 'permission.usr_has_object_perm',
458             alias => 'has_perm',
459             column => 'id',
460             params => []
461         } ]
462     },
463     from => 'au',
464     where => {},
465 };
466
467 sub allowed {
468         my( $self, $perm, $org, $object, $hint ) = @_;
469         my $uid = $self->requestor->id;
470         $org ||= $self->requestor->ws_ou;
471
472     my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
473
474     for $perm (@$perms) {
475             $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
476     
477         if($object) {
478             my $params;
479             if(ref $object) {
480                 # determine the ID field and json_hint from the object
481                 my $id_field = $object->Identity;
482                 $params = [$perm, $object->json_hint, $object->$id_field];
483             } else {
484                 # we were passed an object-id and json_hint
485                 $params = [$perm, $hint, $object];
486             }
487             push(@$params, $org) if $org;
488             $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
489             $OBJECT_PERM_QUERY->{where}->{id} = $uid;
490             return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
491
492         } else {
493             $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
494             $PERM_QUERY->{where}->{id} = $uid;
495             return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
496         }
497     }
498
499     # set the perm failure event if the permission check returned false
500         my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
501         $self->event($e);
502         return undef;
503 }
504
505
506 # -----------------------------------------------------------------------------
507 # Returns the list of object IDs this user has object-specific permissions for
508 # -----------------------------------------------------------------------------
509 sub objects_allowed {
510     my($self, $perm, $obj_type) = @_;
511
512     my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
513     my @ids;
514
515     for $perm (@$perms) {
516         my $query = {
517             select => {puopm => ['object_id']},
518             from => {
519                 puopm => {
520                     ppl => {field => 'id',fkey => 'perm'}
521                 }
522             },
523             where => {
524                 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
525                 '+ppl' => {code => $perm}
526             }
527         };
528     
529         my $list = $self->json_query($query);
530         push(@ids, 0+$_->{object_id}) for @$list;
531     }
532
533    my %trim;
534    $trim{$_} = 1 for @ids;
535    return [ keys %trim ];
536 }
537
538
539 # -----------------------------------------------------------------------------
540 # checks the appropriate perm for the operation
541 # -----------------------------------------------------------------------------
542 sub _checkperm {
543         my( $self, $ptype, $action, $org ) = @_;
544         $org ||= $self->requestor->ws_ou;
545         my $perm = $PERMS{$ptype}{$action};
546         if( $perm ) {
547                 return undef if $self->perm_checked($perm, $org);
548                 return $self->event unless $self->allowed($perm, $org);
549         } else {
550                 $self->log(I, "no perm provided for $ptype.$action");
551         }
552         return undef;
553 }
554
555
556
557 # -----------------------------------------------------------------------------
558 # Logs update actions to the activity log
559 # -----------------------------------------------------------------------------
560 sub log_activity {
561         my( $self, $type, $action, $arg ) = @_;
562         my $str = "$type.$action";
563         $str .= _prop_string($arg);
564         $self->log(A, $str);
565 }
566
567
568
569 sub _prop_string {
570         my $obj = shift;
571         my @props = $obj->properties;
572         my $str = "";
573         for(@props) {
574                 my $prop = $obj->$_() || "";
575                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
576                 $str .= " $_=$prop";
577         }
578         return $str;
579 }
580
581
582 sub __arg_to_string {
583         my $arg = shift;
584         return "" unless defined $arg;
585         if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
586         my $idf = $arg->Identity;
587                 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
588         }
589         return OpenSRF::Utils::JSON->perl2JSON($arg);
590         return "";
591 }
592
593
594 # -----------------------------------------------------------------------------
595 # This does the actual storage query.
596 #
597 # 'search' calls become search_where calls and $arg can be a search hash or
598 # an array-ref of storage search options.  
599 #
600 # 'retrieve' expects an id
601 # 'update' expects an object
602 # 'create' expects an object
603 # 'delete' expects an object
604 #
605 # All methods return true on success and undef on failure.  On failure, 
606 # $e->event is set to the generated event.  
607 # Note: this method assumes that updating a non-changed object and 
608 # thereby receiving a 0 from storage, is a successful update.  
609 #
610 # The method will therefore return true so the caller can just do 
611 # $e->update_blah($x) or return $e->event;
612 # The true value returned from storage for all methods will be stored in 
613 # $e->data, until the next method is called.
614 #
615 # not-found events are generated on retrieve and serach methods.
616 # action=search methods will return [] (==true) if no data is found.  If the
617 # caller is interested in the not found event, they can do:  
618 # return $e->event unless @$results; 
619 # -----------------------------------------------------------------------------
620 sub runmethod {
621         my( $self, $action, $type, $arg, $options ) = @_;
622
623    $options ||= {};
624
625         if( $action eq 'retrieve' ) {
626                 if(! defined($arg) ) {
627                         $self->log(W,"$action $type called with no ID...");
628                         $self->event(_mk_not_found($type, $arg));
629                         return undef;
630                 } elsif( ref($arg) =~ /Fieldmapper/ ) {
631                         $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
632             my $idf = $arg->Identity;
633                         $arg = $arg->$idf;
634                 }
635         }
636
637         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
638         my $method = $self->app.".direct.$type.$action";
639
640         if( $action eq 'search' ) {
641                 $method .= '.atomic';
642
643         } elsif( $action eq 'batch_retrieve' ) {
644                 $action = 'search';
645                 @arg = ( { id => $arg } );
646                 $method =~ s/batch_retrieve/search/o;
647                 $method .= '.atomic';
648
649         } elsif( $action eq 'retrieve_all' ) {
650                 $action = 'search';
651                 $method =~ s/retrieve_all/search/o;
652                 my $tt = $type;
653                 $tt =~ s/\./::/og;
654                 my $fmobj = "Fieldmapper::$tt";
655                 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
656                 $method .= '.atomic';
657         }
658
659         $method =~ s/search/id_list/o if $options->{idlist};
660
661     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
662     $self->timeout($$options{timeout});
663
664         # remove any stale events
665         $self->clear_event;
666
667         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
668                 if(!($self->{xact} or $always_xact)) {
669                         $logger->error("Attempt to update DB while not in a transaction : $method");
670                         throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
671                 }
672                 $self->log_activity($type, $action, $arg);
673         }
674
675         if($$options{checkperm}) {
676                 my $a = ($action eq 'search') ? 'retrieve' : $action;
677                 my $e = $self->_checkperm($type, $a, $$options{permorg});
678                 if($e) {
679                         $self->event($e);
680                         return undef;
681                 }
682         }
683
684         my $obj; 
685         my $err;
686
687         try {
688                 $obj = $self->request($method, @arg);
689         } catch Error with { $err = shift; };
690         
691
692         if(!defined $obj) {
693                 $self->log(I, "request returned no data : $method");
694
695                 if( $action eq 'retrieve' ) {
696                         $self->event(_mk_not_found($type, $arg));
697
698                 } elsif( $action eq 'update' or 
699                                 $action eq 'delete' or $action eq 'create' ) {
700                         my $evt = OpenILS::Event->new(
701                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
702                         $self->event($evt);
703                 }
704
705                 if( $err ) {
706                         $self->event( 
707                                 OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
708                                         payload => $arg, debug => "$err" ));
709                         return undef;
710                 }
711
712                 return undef;
713         }
714
715         if( $action eq 'create' and $obj == 0 ) {
716                 my $evt = OpenILS::Event->new(
717                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
718                 $self->event($evt);
719                 return undef;
720         }
721
722         # If we havn't dealt with the error in a nice way, go ahead and throw it
723         if( $err ) {
724                 $self->event( 
725                         OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
726                                 payload => $arg, debug => "$err" ));
727                 return undef;
728         }
729
730         if( $action eq 'search' ) {
731                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
732                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
733         }
734
735         if( $action eq 'create' ) {
736         my $idf = $obj->Identity;
737                 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
738                 $arg->$idf($obj->$idf);
739         }
740
741         $self->data($obj); # cache the data for convenience
742
743         return ($obj) ? $obj : 1;
744 }
745
746
747 sub _mk_not_found {
748         my( $type, $arg ) = @_;
749         (my $t = $type) =~ s/\./_/og;
750         $t = uc($t);
751         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
752 }
753
754
755
756 # utility method for loading
757 sub __fm2meth { 
758         my $str = shift;
759         my $sep = shift;
760         $str =~ s/Fieldmapper:://o;
761         $str =~ s/::/$sep/g;
762         return $str;
763 }
764
765
766 # -------------------------------------------------------------
767 # Load up the methods from the FM classes
768 # -------------------------------------------------------------
769 my $map = $Fieldmapper::fieldmap;
770 for my $object (keys %$map) {
771         my $obj = __fm2meth($object,'_');
772         my $type = __fm2meth($object, '.');
773
774         my $update = "update_$obj";
775         my $updatef = 
776                 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
777         eval $updatef;
778
779         my $retrieve = "retrieve_$obj";
780         my $retrievef = 
781                 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
782         eval $retrievef;
783
784         my $search = "search_$obj";
785         my $searchf = 
786                 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
787         eval $searchf;
788
789         my $create = "create_$obj";
790         my $createf = 
791                 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
792         eval $createf;
793
794         my $delete = "delete_$obj";
795         my $deletef = 
796                 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
797         eval $deletef;
798
799         my $bretrieve = "batch_retrieve_$obj";
800         my $bretrievef = 
801                 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
802         eval $bretrievef;
803
804         my $retrieveall = "retrieve_all_$obj";
805         my $retrieveallf = 
806                 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
807         eval $retrieveallf;
808 }
809
810 sub json_query {
811     my( $self, $arg, $options ) = @_;
812     $options ||= {};
813         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
814     my $method = $self->app.'.json_query.atomic';
815     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
816
817     $self->timeout($$options{timeout});
818         $self->clear_event;
819     my $obj;
820     my $err;
821     
822     try {
823         $obj = $self->request($method, @arg);
824     } catch Error with { $err = shift; };
825
826     if( $err ) {
827         $self->event(
828             OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
829             payload => $arg, debug => "$err" ));
830         return undef;
831     }
832
833     $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));
834     return $obj;
835 }
836
837
838
839 1;
840
841