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