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