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