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