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