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