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