Support _check_debug options.
[ZOOM-Perl-moved-to-github.git] / lib / ZOOM.pm
1 # $Id: ZOOM.pm,v 1.45 2007-02-13 15:31:26 mike Exp $
2
3 use strict;
4 use warnings;
5 use IO::File;
6 use Net::Z3950::ZOOM;
7
8
9 package ZOOM;
10
11 # Member naming convention: hash-element names which begin with an
12 # underscore represent underlying ZOOM-C object descriptors; those
13 # which lack them represent Perl's ZOOM objects.  (The same convention
14 # is used in naming local variables where appropriate.)
15 #
16 # So, for example, the ZOOM::Connection class has an {_conn} element,
17 # which is a pointer to the ZOOM-C Connection object; but the
18 # ZOOM::ResultSet class has a {conn} element, which is a reference to
19 # the Perl-level Connection object by which it was created.  (It may
20 # be that we find we have no need for these references, but for now
21 # they are retained.)
22 #
23 # To get at the underlying ZOOM-C connection object of a result-set
24 # (if you ever needed to do such a thing, which you probably don't)
25 # you'd use $rs->{conn}->_conn().
26
27 # ----------------------------------------------------------------------------
28
29 # The "Error" package contains constants returned as error-codes.
30 package ZOOM::Error;
31 sub NONE { Net::Z3950::ZOOM::ERROR_NONE }
32 sub CONNECT { Net::Z3950::ZOOM::ERROR_CONNECT }
33 sub MEMORY { Net::Z3950::ZOOM::ERROR_MEMORY }
34 sub ENCODE { Net::Z3950::ZOOM::ERROR_ENCODE }
35 sub DECODE { Net::Z3950::ZOOM::ERROR_DECODE }
36 sub CONNECTION_LOST { Net::Z3950::ZOOM::ERROR_CONNECTION_LOST }
37 sub ZINIT { Net::Z3950::ZOOM::ERROR_INIT }
38 sub INTERNAL { Net::Z3950::ZOOM::ERROR_INTERNAL }
39 sub TIMEOUT { Net::Z3950::ZOOM::ERROR_TIMEOUT }
40 sub UNSUPPORTED_PROTOCOL { Net::Z3950::ZOOM::ERROR_UNSUPPORTED_PROTOCOL }
41 sub UNSUPPORTED_QUERY { Net::Z3950::ZOOM::ERROR_UNSUPPORTED_QUERY }
42 sub INVALID_QUERY { Net::Z3950::ZOOM::ERROR_INVALID_QUERY }
43 sub CQL_PARSE { Net::Z3950::ZOOM::ERROR_CQL_PARSE }
44 sub CQL_TRANSFORM { Net::Z3950::ZOOM::ERROR_CQL_TRANSFORM }
45 sub CCL_CONFIG { Net::Z3950::ZOOM::ERROR_CCL_CONFIG }
46 sub CCL_PARSE { Net::Z3950::ZOOM::ERROR_CCL_PARSE }
47 # The following are added specifically for this OO interface
48 sub CREATE_QUERY { 20001 }
49 sub QUERY_CQL { 20002 }
50 sub QUERY_PQF { 20003 }
51 sub SORTBY { 20004 }
52 sub CLONE { 20005 }
53 sub PACKAGE { 20006 }
54 sub SCANTERM { 20007 }
55 sub LOGLEVEL { 20008 }
56
57 # Separate space for CCL errors.  Great.
58 package ZOOM::CCL::Error;
59 sub OK { Net::Z3950::ZOOM::CCL_ERR_OK }
60 sub TERM_EXPECTED { Net::Z3950::ZOOM::CCL_ERR_TERM_EXPECTED }
61 sub RP_EXPECTED { Net::Z3950::ZOOM::CCL_ERR_RP_EXPECTED }
62 sub SETNAME_EXPECTED { Net::Z3950::ZOOM::CCL_ERR_SETNAME_EXPECTED }
63 sub OP_EXPECTED { Net::Z3950::ZOOM::CCL_ERR_OP_EXPECTED }
64 sub BAD_RP { Net::Z3950::ZOOM::CCL_ERR_BAD_RP }
65 sub UNKNOWN_QUAL { Net::Z3950::ZOOM::CCL_ERR_UNKNOWN_QUAL }
66 sub DOUBLE_QUAL { Net::Z3950::ZOOM::CCL_ERR_DOUBLE_QUAL }
67 sub EQ_EXPECTED { Net::Z3950::ZOOM::CCL_ERR_EQ_EXPECTED }
68 sub BAD_RELATION { Net::Z3950::ZOOM::CCL_ERR_BAD_RELATION }
69 sub TRUNC_NOT_LEFT { Net::Z3950::ZOOM::CCL_ERR_TRUNC_NOT_LEFT }
70 sub TRUNC_NOT_BOTH { Net::Z3950::ZOOM::CCL_ERR_TRUNC_NOT_BOTH }
71 sub TRUNC_NOT_RIGHT { Net::Z3950::ZOOM::CCL_ERR_TRUNC_NOT_RIGHT }
72
73 # The "Event" package contains constants returned by last_event()
74 package ZOOM::Event;
75 sub NONE { Net::Z3950::ZOOM::EVENT_NONE }
76 sub CONNECT { Net::Z3950::ZOOM::EVENT_CONNECT }
77 sub SEND_DATA { Net::Z3950::ZOOM::EVENT_SEND_DATA }
78 sub RECV_DATA { Net::Z3950::ZOOM::EVENT_RECV_DATA }
79 sub TIMEOUT { Net::Z3950::ZOOM::EVENT_TIMEOUT }
80 sub UNKNOWN { Net::Z3950::ZOOM::EVENT_UNKNOWN }
81 sub SEND_APDU { Net::Z3950::ZOOM::EVENT_SEND_APDU }
82 sub RECV_APDU { Net::Z3950::ZOOM::EVENT_RECV_APDU }
83 sub RECV_RECORD { Net::Z3950::ZOOM::EVENT_RECV_RECORD }
84 sub RECV_SEARCH { Net::Z3950::ZOOM::EVENT_RECV_SEARCH }
85 sub ZEND { Net::Z3950::ZOOM::EVENT_END }
86
87 # ----------------------------------------------------------------------------
88
89 package ZOOM;
90
91 sub diag_str {
92     my($code) = @_;
93
94     # Special cases for error specific to the OO layer
95     if ($code == ZOOM::Error::CREATE_QUERY) {
96         return "can't create query object";
97     } elsif ($code == ZOOM::Error::QUERY_CQL) {
98         return "can't set CQL query";
99     } elsif ($code == ZOOM::Error::QUERY_PQF) {
100         return "can't set prefix query";
101     } elsif ($code == ZOOM::Error::SORTBY) {
102         return "can't set sort-specification";
103     } elsif ($code == ZOOM::Error::CLONE) {
104         return "can't clone record";
105     } elsif ($code == ZOOM::Error::PACKAGE) {
106         return "can't create package";
107     } elsif ($code == ZOOM::Error::SCANTERM) {
108         return "can't retrieve term from scan-set";
109     } elsif ($code == ZOOM::Error::LOGLEVEL) {
110         return "unregistered log-level";
111     }
112
113     return Net::Z3950::ZOOM::diag_str($code);
114 }
115
116 sub event_str {
117     return Net::Z3950::ZOOM::event_str(@_);
118 }
119
120 sub event {
121     my($connsref) = @_;
122
123     my @_connsref = map { $_->_conn() } @$connsref;
124     return Net::Z3950::ZOOM::event(\@_connsref);
125 }
126
127 sub _oops {
128     my($code, $addinfo, $diagset) = @_;
129
130     die new ZOOM::Exception($code, undef, $addinfo, $diagset);
131 }
132
133 # ----------------------------------------------------------------------------
134
135 package ZOOM::Exception;
136
137 sub new {
138     my $class = shift();
139     my($code, $message, $addinfo, $diagset) = @_;
140
141     $diagset ||= "ZOOM";
142     if (uc($diagset) eq "ZOOM" || uc($diagset) eq "BIB-1") {
143         $message ||= ZOOM::diag_str($code);
144     } else {
145         # Should fill in messages for other diagsets, too.
146     }
147
148     return bless {
149         code => $code,
150         message => $message,
151         addinfo => $addinfo,
152         diagset => $diagset,
153     }, $class;
154 }
155
156 sub code {
157     my $this = shift();
158     return $this->{code};
159 }
160
161 sub message {
162     my $this = shift();
163     return $this->{message};
164 }
165
166 sub addinfo {
167     my $this = shift();
168     return $this->{addinfo};
169 }
170
171 sub diagset {
172     my $this = shift();
173     return $this->{diagset};
174 }
175
176 sub render {
177     my $this = shift();
178     my $res = "ZOOM error " . $this->code() . ' "' . $this->message() . '"';
179     $res .= ' (addinfo: "' . $this->addinfo() . '")' if $this->addinfo();
180     $res .= " from diag-set '" . $this->diagset() . "'" if $this->diagset();
181     return $res;
182 }
183
184 # This means that untrapped exceptions render nicely.
185 use overload '""' => \&render;
186
187 # ----------------------------------------------------------------------------
188
189 package ZOOM::Options;
190
191 sub new {
192     my $class = shift();
193     my($p1, $p2) = @_;
194
195     my $opts;
196     if (@_ == 0) {
197         $opts = Net::Z3950::ZOOM::options_create();
198     } elsif (@_ == 1) {
199         $opts = Net::Z3950::ZOOM::options_create_with_parent($p1->_opts());
200     } elsif (@_ == 2) {
201         $opts = Net::Z3950::ZOOM::options_create_with_parent2($p1->_opts(),
202                                                               $p2->_opts());
203     } else {
204         die "can't make $class object with more than 2 parents";
205     }
206
207     return bless {
208         _opts => $opts,
209     }, $class;
210 }
211
212 # PRIVATE to this class and ZOOM::Connection::create() and
213 # ZOOM::Connection::package()
214 #
215 sub _opts {
216     my $this = shift();
217
218     my $_opts = $this->{_opts};
219     die "{_opts} undefined: has this Options block been destroy()ed?"
220         if !defined $_opts;
221
222     return $_opts;
223 }
224
225 sub option {
226     my $this = shift();
227     my($key, $value) = @_;
228
229     my $oldval = Net::Z3950::ZOOM::options_get($this->_opts(), $key);
230     Net::Z3950::ZOOM::options_set($this->_opts(), $key, $value)
231         if defined $value;
232
233     return $oldval;
234 }
235
236 sub option_binary {
237     my $this = shift();
238     my($key, $value) = @_;
239
240     my $dummylen = 0;
241     my $oldval = Net::Z3950::ZOOM::options_getl($this->_opts(),
242                                                 $key, $dummylen);
243     Net::Z3950::ZOOM::options_setl($this->_opts(), $key,
244                                    $value, length($value))
245         if defined $value;
246
247     return $oldval;
248 }
249
250 # This is a bit stupid, since the scalar values that Perl returns from
251 # option() can be used as a boolean; but it's just possible that some
252 # applications will rely on ZOOM_options_get_bool()'s idiosyncratic
253 # interpretation of what constitutes truth.
254 #
255 sub bool {
256     my $this = shift();
257     my($key, $default) = @_;
258
259     return Net::Z3950::ZOOM::options_get_bool($this->_opts(), $key, $default);
260 }
261
262 # .. and the next two are even more stupid
263 sub int {
264     my $this = shift();
265     my($key, $default) = @_;
266
267     return Net::Z3950::ZOOM::options_get_int($this->_opts(), $key, $default);
268 }
269
270 sub set_int {
271     my $this = shift();
272     my($key, $value) = @_;
273
274     Net::Z3950::ZOOM::options_set_int($this->_opts(), $key, $value);
275 }
276
277 #   ### Feel guilty.  Feel very, very guilty.  I've not been able to
278 #       get the callback memory-management right in "ZOOM.xs", with
279 #       the result that the values of $function and $udata passed into
280 #       this function, which are on the stack, have sometimes been
281 #       freed by the time they're used by __ZOOM_option_callback(),
282 #       with hilarious results.  To avoid this, I copy the values into
283 #       module-scoped globals, and pass _those_ into the extension
284 #       function.  To avoid overwriting those globals by subsequent
285 #       calls, I keep all the old ones, pushed onto the @_function and
286 #       @_udata arrays, which means that THIS FUNCTION LEAKS MEMORY
287 #       LIKE IT'S GOING OUT OF FASHION.  Not nice.  One day, I should
288 #       fix this, but for now there's more important fish to fry.
289 #
290 my(@_function, @_udata);
291 sub set_callback {
292     my $o1 = shift();
293     my($function, $udata) = @_;
294
295     push @_function, $function;
296     push @_udata, $udata;
297     Net::Z3950::ZOOM::options_set_callback($o1->_opts(),
298                                            $_function[-1], $_udata[-1]);
299 }
300
301 sub destroy {
302     my $this = shift();
303
304     Net::Z3950::ZOOM::options_destroy($this->_opts());
305     $this->{_opts} = undef;
306 }
307
308
309 # ----------------------------------------------------------------------------
310
311 package ZOOM::Connection;
312
313 sub new {
314     my $class = shift();
315     my($host, $port, @options) = @_;
316
317     my $conn = $class->create(@options);
318     $conn->{host} = $host;
319     $conn->{port} = $port;
320
321     Net::Z3950::ZOOM::connection_connect($conn->_conn(), $host, $port || 0);
322     $conn->_check();
323
324     return $conn;
325 }
326
327 # PRIVATE to this class, to ZOOM::event() and to ZOOM::Query::CQL2RPN::new()
328 sub _conn {
329     my $this = shift();
330
331     my $_conn = $this->{_conn};
332     die "{_conn} undefined: has this Connection been destroy()ed?"
333         if !defined $_conn;
334
335     return $_conn;
336 }
337
338 sub _check {
339     my $this = shift();
340
341     my($errcode, $errmsg, $addinfo, $diagset) = (undef, "x", "x", "x");
342     $errcode = Net::Z3950::ZOOM::connection_error_x($this->_conn(), $errmsg,
343                                                     $addinfo, $diagset);
344     if ($errcode) {
345         if ($this->option("_check_debug")) {
346             print STDERR "ZOOM WARNING!  $this->check() failed with error $diagset:$errcode ($errmsg) $addinfo\n";
347             print STDERR "SIG{SEGV} ", (defined $SIG{SEGV} ? ("= '" . $SIG{SEGV} . "'") : "undefined"), "'\n";
348             print STDERR "SIG{__DIE__} ", (defined $SIG{__DIE__} ? ("= '" . $SIG{__DIE__} , "'") : "undefined"), "'\n";
349         }
350         die new ZOOM::Exception($errcode, $errmsg, $addinfo, $diagset);
351     }
352 }
353
354 sub create {
355     my $class = shift();
356     my(@options) = @_;
357
358     my $_opts;
359     if (@_ == 1) {
360         $_opts = $_[0]->_opts();
361     } else {
362         $_opts = Net::Z3950::ZOOM::options_create();
363         while (@options >= 2) {
364             my $key = shift(@options);
365             my $val = shift(@options);
366             Net::Z3950::ZOOM::options_set($_opts, $key, $val);
367         }
368
369         die "Odd number of options specified"
370             if @options;
371     }
372
373     my $_conn = Net::Z3950::ZOOM::connection_create($_opts);
374     my $conn = bless {
375         host => undef,
376         port => undef,
377         _conn => $_conn,
378     }, $class;
379     return $conn;
380 }
381
382 sub error_x {
383     my $this = shift();
384
385     my($errcode, $errmsg, $addinfo, $diagset) = (undef, "dummy", "dummy", "d");
386     $errcode = Net::Z3950::ZOOM::connection_error_x($this->_conn(), $errmsg,
387                                                     $addinfo, $diagset);
388     return wantarray() ? ($errcode, $errmsg, $addinfo, $diagset) : $errcode;
389 }
390
391 sub errcode {
392     my $this = shift();
393     return Net::Z3950::ZOOM::connection_errcode($this->_conn());
394 }
395
396 sub errmsg {
397     my $this = shift();
398     return Net::Z3950::ZOOM::connection_errmsg($this->_conn());
399 }
400
401 sub addinfo {
402     my $this = shift();
403     return Net::Z3950::ZOOM::connection_addinfo($this->_conn());
404 }
405
406 sub diagset {
407     my $this = shift();
408     return Net::Z3950::ZOOM::connection_diagset($this->_conn());
409 }
410
411 sub connect {
412     my $this = shift();
413     my($host, $port) = @_;
414
415     $port = 0 if !defined $port;
416     Net::Z3950::ZOOM::connection_connect($this->_conn(), $host, $port);
417     $this->_check();
418     # No return value
419 }
420
421 sub option {
422     my $this = shift();
423     my($key, $value) = @_;
424
425     my $oldval = Net::Z3950::ZOOM::connection_option_get($this->_conn(), $key);
426     Net::Z3950::ZOOM::connection_option_set($this->_conn(), $key, $value)
427         if defined $value;
428
429     return $oldval;
430 }
431
432 sub option_binary {
433     my $this = shift();
434     my($key, $value) = @_;
435
436     my $dummylen = 0;
437     my $oldval = Net::Z3950::ZOOM::connection_option_getl($this->_conn(),
438                                                           $key, $dummylen);
439     Net::Z3950::ZOOM::connection_option_setl($this->_conn(), $key,
440                                              $value, length($value))
441         if defined $value;
442
443     return $oldval;
444 }
445
446 sub search {
447     my $this = shift();
448     my($query) = @_;
449
450     my $_rs = Net::Z3950::ZOOM::connection_search($this->_conn(),
451                                                   $query->_query());
452     $this->_check();
453     return _new ZOOM::ResultSet($this, $query, $_rs);
454 }
455
456 sub search_pqf {
457     my $this = shift();
458     my($pqf) = @_;
459
460     my $_rs = Net::Z3950::ZOOM::connection_search_pqf($this->_conn(), $pqf);
461     $this->_check();
462     return _new ZOOM::ResultSet($this, $pqf, $_rs);
463 }
464
465 sub scan_pqf {
466     my $this = shift();
467     my($startterm) = @_;
468
469     my $_ss = Net::Z3950::ZOOM::connection_scan($this->_conn(), $startterm);
470     $this->_check();
471     return _new ZOOM::ScanSet($this, $startterm, $_ss);
472 }
473
474 sub scan {
475     my $this = shift();
476     my($query) = @_;
477
478     my $_ss = Net::Z3950::ZOOM::connection_scan1($this->_conn(),
479                                                  $query->_query());
480     $this->_check();
481     return _new ZOOM::ScanSet($this, $query, $_ss);
482 }
483
484 sub package {
485     my $this = shift();
486     my($options) = @_;
487
488     my $_o = defined $options ? $options->_opts() :
489         Net::Z3950::ZOOM::options_create();
490     my $_p = Net::Z3950::ZOOM::connection_package($this->_conn(), $_o)
491         or ZOOM::_oops(ZOOM::Error::PACKAGE);
492
493     return _new ZOOM::Package($this, $options, $_p);
494 }
495
496 sub last_event {
497     my $this = shift();
498
499     return Net::Z3950::ZOOM::connection_last_event($this->_conn());
500 }
501
502 sub is_idle {
503     my $this = shift();
504
505     return Net::Z3950::ZOOM::connection_is_idle($this->_conn());
506 }
507
508 sub peek_event {
509     my $this = shift();
510
511     return Net::Z3950::ZOOM::connection_peek_event($this->_conn());
512 }
513
514 sub destroy {
515     my $this = shift();
516
517     Net::Z3950::ZOOM::connection_destroy($this->_conn());
518     $this->{_conn} = undef;
519 }
520
521
522 # ----------------------------------------------------------------------------
523
524 package ZOOM::Query;
525
526 sub new {
527     my $class = shift();
528     die "You can't create $class objects: it's a virtual base class";
529 }
530
531 # PRIVATE to this class and ZOOM::Connection::search()
532 sub _query {
533     my $this = shift();
534
535     my $_query = $this->{_query};
536     die "{_query} undefined: has this Query been destroy()ed?"
537         if !defined $_query;
538
539     return $_query;
540 }
541
542 sub sortby {
543     my $this = shift();
544     my($sortby) = @_;
545
546     Net::Z3950::ZOOM::query_sortby($this->_query(), $sortby) == 0
547         or ZOOM::_oops(ZOOM::Error::SORTBY, $sortby);
548 }
549
550 sub destroy {
551     my $this = shift();
552
553     Net::Z3950::ZOOM::query_destroy($this->_query());
554     $this->{_query} = undef;
555 }
556
557
558 package ZOOM::Query::CQL;
559 our @ISA = qw(ZOOM::Query);
560
561 sub new {
562     my $class = shift();
563     my($string) = @_;
564
565     my $q = Net::Z3950::ZOOM::query_create()
566         or ZOOM::_oops(ZOOM::Error::CREATE_QUERY);
567     Net::Z3950::ZOOM::query_cql($q, $string) == 0
568         or ZOOM::_oops(ZOOM::Error::QUERY_CQL, $string);
569
570     return bless {
571         _query => $q,
572     }, $class;
573 }
574
575
576 package ZOOM::Query::CQL2RPN;
577 our @ISA = qw(ZOOM::Query);
578
579 sub new {
580     my $class = shift();
581     my($string, $conn) = @_;
582
583     my $q = Net::Z3950::ZOOM::query_create()
584         or ZOOM::_oops(ZOOM::Error::CREATE_QUERY);
585     # check() throws the exception we want; but we only want it on failure!
586     Net::Z3950::ZOOM::query_cql2rpn($q, $string, $conn->_conn()) == 0
587         or $conn->_check();
588
589     return bless {
590         _query => $q,
591     }, $class;
592 }
593
594
595 # We have to work around the retarded ZOOM_query_ccl2rpn() API
596 package ZOOM::Query::CCL2RPN;
597 our @ISA = qw(ZOOM::Query);
598
599 sub new {
600     my $class = shift();
601     my($string, $conn) = @_;
602
603     my $q = Net::Z3950::ZOOM::query_create()
604         or ZOOM::_oops(ZOOM::Error::CREATE_QUERY);
605
606     my $config = $conn->option("cclqual");
607     if (!defined $config) {
608         my $cclfile = $conn->option("cclfile")
609             or ZOOM::_oops(ZOOM::Error::CCL_CONFIG,
610                            "no 'cclqual' or 'cclfile' specified");
611         my $fh = new IO::File("<$cclfile")
612             or ZOOM::_oops(ZOOM::Error::CCL_CONFIG,
613                            "can't open cclfile '$cclfile': $!");
614         $config = join("", <$fh>);
615         $fh->close();
616     }
617
618     my($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0, "", 0);
619     if (Net::Z3950::ZOOM::query_ccl2rpn($q, $string, $config,
620                                         $ccl_errcode, $ccl_errstr,
621                                         $ccl_errpos) < 0) {
622         # We have no use for $ccl_errcode or $ccl_errpos
623         ZOOM::_oops(ZOOM::Error::CCL_PARSE, $ccl_errstr);
624     }
625
626     return bless {
627         _query => $q,
628     }, $class;
629 }
630
631
632 package ZOOM::Query::PQF;
633 our @ISA = qw(ZOOM::Query);
634
635 sub new {
636     my $class = shift();
637     my($string) = @_;
638
639     my $q = Net::Z3950::ZOOM::query_create()
640         or ZOOM::_oops(ZOOM::Error::CREATE_QUERY);
641     Net::Z3950::ZOOM::query_prefix($q, $string) == 0
642         or ZOOM::_oops(ZOOM::Error::QUERY_PQF, $string);
643
644     return bless {
645         _query => $q,
646     }, $class;
647 }
648
649
650 # ----------------------------------------------------------------------------
651
652 package ZOOM::ResultSet;
653
654 sub new {
655     my $class = shift();
656     die "You can't create $class objects directly";
657 }
658
659 # PRIVATE to ZOOM::Connection::search() and ZOOM::Connection::search_pqf()
660 sub _new {
661     my $class = shift();
662     my($conn, $query, $_rs) = @_;
663
664     return bless {
665         conn => $conn,
666         query => $query,        # This is not currently used, which is
667                                 # just as well since it could be
668                                 # either a string (when the RS is
669                                 # created with search_pqf()) or a
670                                 # ZOOM::Query object (when it's
671                                 # created with search())
672         _rs => $_rs,
673     }, $class;
674 }
675
676 # PRIVATE to this class
677 sub _rs {
678     my $this = shift();
679
680     my $_rs = $this->{_rs};
681     die "{_rs} undefined: has this ResultSet been destroy()ed?"
682         if !defined $_rs;
683
684     return $_rs;
685 }
686
687 sub option {
688     my $this = shift();
689     my($key, $value) = @_;
690
691     my $oldval = Net::Z3950::ZOOM::resultset_option_get($this->_rs(), $key);
692     Net::Z3950::ZOOM::resultset_option_set($this->_rs(), $key, $value)
693         if defined $value;
694
695     return $oldval;
696 }
697
698 sub size {
699     my $this = shift();
700
701     return Net::Z3950::ZOOM::resultset_size($this->_rs());
702 }
703
704 sub record {
705     my $this = shift();
706     my($which) = @_;
707
708     my $_rec = Net::Z3950::ZOOM::resultset_record($this->_rs(), $which);
709     $this->{conn}->_check();
710
711     # Even if no error has occurred, I think record() might
712     # legitimately return undef if we're running in asynchronous mode
713     # and the record just hasn't been retrieved yet.  This goes double
714     # for record_immediate().
715     return undef if !defined $_rec;
716
717     # For some reason, I have to use the explicit "->" syntax in order
718     # to invoke the ZOOM::Record constructor here, even though I don't
719     # have to do the same for _new ZOOM::ResultSet above.  Weird.
720     return ZOOM::Record->_new($this, $which, $_rec);
721 }
722
723 sub record_immediate {
724     my $this = shift();
725     my($which) = @_;
726
727     my $_rec = Net::Z3950::ZOOM::resultset_record_immediate($this->_rs(),
728                                                             $which);
729     $this->{conn}->_check();
730     # The record might legitimately not be there yet
731     return undef if !defined $_rec;
732
733     return ZOOM::Record->_new($this, $which, $_rec);
734 }
735
736 sub cache_reset {
737     my $this = shift();
738
739     Net::Z3950::ZOOM::resultset_cache_reset($this->_rs());
740 }
741
742 sub records {
743     my $this = shift();
744     my($start, $count, $return_records) = @_;
745
746     # If the request is out of range, ZOOM-C will currently (as of YAZ
747     # 2.1.38) no-op: it understandably refuses to build and send a
748     # known-bad APDU, but it doesn't set a diagnostic as it ought.  So
749     # for now, we do it here.  It would be more polite to stash the
750     # error-code in the ZOOM-C connection object for subsequent
751     # discovery (which is what ZOOM-C will presumably do itself when
752     # it's fixed) but since there is no API that allows us to do that,
753     # we just have to throw the exception right now.  That's probably
754     # OK for synchronous applications, but not really for
755     # multiplexers.
756     my $size = $this->size();
757     if ($start + $count-1 >= $size) {
758         # BIB-1 diagnostic 13 is "Present request out-of-range"
759         ZOOM::_oops(13, undef, "BIB-1");
760     }
761
762     my $raw = Net::Z3950::ZOOM::resultset_records($this->_rs(), $start, $count,
763                                                   $return_records);
764     # By design, $raw may be undefined (if $return_records is true)
765     return undef if !defined $raw;
766
767     # We need to package up the returned records in ZOOM::Record objects
768     my @res = ();
769     for my $i (0 .. @$raw-1) {
770         my $_rec = $raw->[$i];
771         if (!defined $_rec) {
772             push @res, undef;
773         } else {
774             push @res, ZOOM::Record->_new($this, $start+$i, $_rec);
775         }
776     }
777
778     return \@res;
779 }
780
781 sub sort {
782     my $this = shift();
783     my($sort_type, $sort_spec) = @_;
784
785     return Net::Z3950::ZOOM::resultset_sort1($this->_rs(),
786                                              $sort_type, $sort_spec);
787 }
788
789 sub destroy {
790     my $this = shift();
791
792     Net::Z3950::ZOOM::resultset_destroy($this->_rs());
793     $this->{_rs} = undef;
794 }
795
796
797 # ----------------------------------------------------------------------------
798
799 package ZOOM::Record;
800
801 sub new {
802     my $class = shift();
803     die "You can't create $class objects directly";
804 }
805
806 # PRIVATE to ZOOM::ResultSet::record(),
807 # ZOOM::ResultSet::record_immediate(), ZOOM::ResultSet::records() and
808 # ZOOM::Record::clone()
809 #
810 sub _new {
811     my $class = shift();
812     my($rs, $which, $_rec) = @_;
813
814     return bless {
815         rs => $rs,
816         which => $which,
817         _rec => $_rec,
818     }, $class;
819 }
820
821 # PRIVATE to this class
822 sub _rec {
823     my $this = shift();
824
825     my $_rec = $this->{_rec};
826     die "{_rec} undefined: has this Record been destroy()ed?"
827         if !defined $_rec;
828
829     return $_rec;
830 }
831
832 sub error {
833     my $this = shift();
834
835     my($errcode, $errmsg, $addinfo, $diagset) = (undef, "dummy", "dummy", "d");
836     $errcode = Net::Z3950::ZOOM::record_error($this->_rec(), $errmsg,
837                                               $addinfo, $diagset);
838
839     return wantarray() ? ($errcode, $errmsg, $addinfo, $diagset) : $errcode;
840 }
841
842 sub exception {
843     my $this = shift();
844
845     my($errcode, $errmsg, $addinfo, $diagset) = $this->error();
846     return undef if $errcode == 0;
847     return new ZOOM::Exception($errcode, $errmsg, $addinfo, $diagset);
848 }
849
850
851 sub render {
852     my $this = shift();
853
854     return $this->get("render", @_);
855 }
856
857 sub raw {
858     my $this = shift();
859
860     return $this->get("raw", @_);
861 }
862
863 sub get {
864     my $this = shift();
865     my($type, $args) = @_;
866
867     $type = "$type;$args" if defined $args;
868     my $len = 0;
869     my $string = Net::Z3950::ZOOM::record_get($this->_rec(), $type, $len);
870     # I don't think we need '$len' at all.  ### Probably the Perl-to-C
871     # glue code should use the value of `len' as well as the opaque
872     # data-pointer returned, to ensure that the SV contains all of the
873     # returned data and does not stop at the first NUL character in
874     # binary data.  Carefully check the ZOOM_record_get() documentation.
875     return $string;
876 }
877
878 sub clone {
879     my $this = shift();
880
881     my $raw = Net::Z3950::ZOOM::record_clone($this->_rec())
882         or ZOOM::_oops(ZOOM::Error::CLONE);
883
884     # Arg 1 (rs) is undefined as the new record doesn't belong to an RS
885     return _new ZOOM::Record(undef, undef, $raw);
886 }
887
888 sub destroy {
889     my $this = shift();
890
891     Net::Z3950::ZOOM::record_destroy($this->_rec());
892     $this->{_rec} = undef;
893 }
894
895
896 # ----------------------------------------------------------------------------
897
898 package ZOOM::ScanSet;
899
900 sub new {
901     my $class = shift();
902     die "You can't create $class objects directly";
903 }
904
905 # PRIVATE to ZOOM::Connection::scan(),
906 sub _new {
907     my $class = shift();
908     my($conn, $startterm, $_ss) = @_;
909
910     return bless {
911         conn => $conn,
912         startterm => $startterm,# This is not currently used, which is
913                                 # just as well since it could be
914                                 # either a string (when the SS is
915                                 # created with scan()) or a
916                                 # ZOOM::Query object (when it's
917                                 # created with scan1())
918         _ss => $_ss,
919     }, $class;
920 }
921
922 # PRIVATE to this class
923 sub _ss {
924     my $this = shift();
925
926     my $_ss = $this->{_ss};
927     die "{_ss} undefined: has this ScanSet been destroy()ed?"
928         if !defined $_ss;
929
930     return $_ss;
931 }
932
933 sub option {
934     my $this = shift();
935     my($key, $value) = @_;
936
937     my $oldval = Net::Z3950::ZOOM::scanset_option_get($this->_ss(), $key);
938     Net::Z3950::ZOOM::scanset_option_set($this->_ss(), $key, $value)
939         if defined $value;
940
941     return $oldval;
942 }
943
944 sub size {
945     my $this = shift();
946
947     return Net::Z3950::ZOOM::scanset_size($this->_ss());
948 }
949
950 sub term {
951     my $this = shift();
952     my($which) = @_;
953
954     my($occ, $len) = (0, 0);
955     my $term = Net::Z3950::ZOOM::scanset_term($this->_ss(), $which,
956                                               $occ, $len)
957         or ZOOM::_oops(ZOOM::Error::SCANTERM);
958
959     die "length of term '$term' differs from returned len=$len"
960         if length($term) != $len;
961
962     return ($term, $occ);
963 }
964
965 sub display_term {
966     my $this = shift();
967     my($which) = @_;
968
969     my($occ, $len) = (0, 0);
970     my $term = Net::Z3950::ZOOM::scanset_display_term($this->_ss(), $which,
971                                                       $occ, $len)
972         or ZOOM::_oops(ZOOM::Error::SCANTERM);
973
974     die "length of display term '$term' differs from returned len=$len"
975         if length($term) != $len;
976
977     return ($term, $occ);
978 }
979
980 sub destroy {
981     my $this = shift();
982
983     Net::Z3950::ZOOM::scanset_destroy($this->_ss());
984     $this->{_ss} = undef;
985 }
986
987
988 # ----------------------------------------------------------------------------
989
990 package ZOOM::Package;
991
992 sub new {
993     my $class = shift();
994     die "You can't create $class objects directly";
995 }
996
997 # PRIVATE to ZOOM::Connection::package(),
998 sub _new {
999     my $class = shift();
1000     my($conn, $options, $_p) = @_;
1001
1002     return bless {
1003         conn => $conn,
1004         options => $options,
1005         _p => $_p,
1006     }, $class;
1007 }
1008
1009 # PRIVATE to this class
1010 sub _p {
1011     my $this = shift();
1012
1013     my $_p = $this->{_p};
1014     die "{_p} undefined: has this Package been destroy()ed?"
1015         if !defined $_p;
1016
1017     return $_p;
1018 }
1019
1020 sub option {
1021     my $this = shift();
1022     my($key, $value) = @_;
1023
1024     my $oldval = Net::Z3950::ZOOM::package_option_get($this->_p(), $key);
1025     Net::Z3950::ZOOM::package_option_set($this->_p(), $key, $value)
1026         if defined $value;
1027
1028     return $oldval;
1029 }
1030
1031 sub send {
1032     my $this = shift();
1033     my($type) = @_;
1034
1035     Net::Z3950::ZOOM::package_send($this->_p(), $type);
1036     $this->{conn}->_check();
1037 }
1038
1039 sub destroy {
1040     my $this = shift();
1041
1042     Net::Z3950::ZOOM::package_destroy($this->_p());
1043     $this->{_p} = undef;
1044 }
1045
1046
1047 # There follows trivial support for YAZ logging.  This is wired out
1048 # into the Net::Z3950::ZOOM package, and we here provide wrapper
1049 # functions -- nothing more than aliases, really -- in the ZOOM::Log
1050 # package.  There really is no point in inventing an OO interface.
1051 #
1052 # Passing @_ directly to the underlying Net::Z3950::ZOOM::* functions
1053 # doesn't work, for reasons that I can't begin to fathom, and that
1054 # don't particularly interest me.  Unpacking into scalars and passing
1055 # those _does_ work, so that's what we do.
1056
1057 package ZOOM::Log;
1058
1059 sub mask_str      { my($a) = @_; Net::Z3950::ZOOM::yaz_log_mask_str($a); }
1060 sub module_level  { my($a) = @_; Net::Z3950::ZOOM::yaz_log_module_level($a); }
1061 sub init          { my($a, $b, $c) = @_;
1062                     Net::Z3950::ZOOM::yaz_log_init($a, $b, $c) }
1063 sub init_file     { my($a) = @_; Net::Z3950::ZOOM::yaz_log_init_file($a) }
1064 sub init_level    { my($a) = @_; Net::Z3950::ZOOM::yaz_log_init_level($a) }
1065 sub init_prefix   { my($a) = @_; Net::Z3950::ZOOM::yaz_log_init_prefix($a) }
1066 sub time_format   { my($a) = @_; Net::Z3950::ZOOM::yaz_log_time_format($a) }
1067 sub init_max_size { my($a) = @_; Net::Z3950::ZOOM::yaz_log_init_max_size($a) }
1068
1069 sub log {
1070     my($level, @message) = @_;
1071
1072     if ($level !~ /^(0x)?\d+$/) {
1073         # Assuming its log-level name, we look it up.
1074         my $num = module_level($level);
1075         ZOOM::_oops(ZOOM::Error::LOGLEVEL, $level)
1076             if $num == 0;
1077         $level = $num;
1078     }
1079
1080     Net::Z3950::ZOOM::yaz_log($level, join("", @message));
1081 }
1082
1083
1084 1;