Update copyright year
[ZOOM-Perl-moved-to-github.git] / lib / ZOOM.pod
1 use strict;
2 use warnings;
3
4 =head1 NAME
5
6 ZOOM - Perl extension implementing the ZOOM API for Information Retrieval
7
8 =head1 SYNOPSIS
9
10  use ZOOM;
11  eval {
12      $conn = new ZOOM::Connection($host, $port,
13                                   databaseName => "mydb");
14      $conn->option(preferredRecordSyntax => "usmarc");
15      $rs = $conn->search_pqf('@attr 1=4 dinosaur');
16      $n = $rs->size();
17      print $rs->record(0)->render();
18  };
19  if ($@) {
20      print "Error ", $@->code(), ": ", $@->message(), "\n";
21  }
22
23 =head1 DESCRIPTION
24
25 This module provides a nice, Perlish implementation of the ZOOM
26 Abstract API described and documented at http://zoom.z3950.org/api/
27
28 the ZOOM module is implemented as a set of thin classes on top of the
29 non-OO functions provided by this distribution's C<Net::Z3950::ZOOM>
30 module, which in 
31 turn is a thin layer on top of the ZOOM-C code supplied as part of
32 Index Data's YAZ Toolkit.  Because ZOOM-C is also the underlying code
33 that implements ZOOM bindings in C++, Visual Basic, Scheme, Ruby, .NET
34 (including C#) and other languages, this Perl module works compatibly
35 with those other implementations.  (Of course, the point of a public
36 API such as ZOOM is that all implementations should be compatible
37 anyway; but knowing that the same code is running is reassuring.)
38
39 The ZOOM module provides two enumerations (C<ZOOM::Error> and
40 C<ZOOM::Event>), three utility functions C<diag_str()>, C<event_str()>
41 and C<event()> in the C<ZOOM> package itself, and eight classes:
42 C<ZOOM::Exception>,
43 C<ZOOM::Options>,
44 C<ZOOM::Connection>,
45 C<ZOOM::Query>,
46 C<ZOOM::ResultSet>,
47 C<ZOOM::Record>,
48 C<ZOOM::ScanSet>
49 and
50 C<ZOOM::Package>.
51 Of these, the Query class is abstract, and has four concrete
52 subclasses:
53 C<ZOOM::Query::CQL>,
54 C<ZOOM::Query::PQF>,
55 C<ZOOM::Query::CQL2RPN>
56 and
57 C<ZOOM::Query::CCL2RPN>.
58 Finally, it also provides a
59 C<ZOOM::Query::Log>
60 module which supplies a useful general-purpose logging facility.
61 Many useful ZOOM applications can be built using only the Connection,
62 ResultSet, Record and Exception classes, as in the example
63 code-snippet above.
64
65 A typical application will begin by creating an Connection object,
66 then using that to execute searches that yield ResultSet objects, then
67 fetching records from the result-sets to yield Record objects.  If an
68 error occurs, an Exception object is thrown and can be dealt with.
69
70 More sophisticated applications might also browse the server's indexes
71 to create a ScanSet, from which indexed terms may be retrieved; others
72 might send ``Extended Services'' Packages to the server, to achieve
73 non-standard tasks such as database creation and record update.
74 Searching using a query syntax other than PQF can be done using an
75 query object of one of the Query subclasses.  Finally, sets of options
76 may be manipulated independently of the objects they are associated
77 with using an Options object.
78
79 In general, method calls throw an exception if anything goes wrong, so
80 you don't need to test for success after each call.  See the section
81 below on the Exception class for details.
82
83 =head1 UTILITY FUNCTIONS
84
85 =head2 ZOOM::diag_str()
86
87  $msg = ZOOM::diag_str(ZOOM::Error::INVALID_QUERY);
88
89 Returns a human-readable English-language string corresponding to the
90 error code that is its own parameter.  This works for any error-code
91 returned from
92 C<ZOOM::Exception::code()>,
93 C<ZOOM::Connection::error_x()>
94 or
95 C<ZOOM::Connection::errcode()>,
96 irrespective of whether it is a member of the C<ZOOM::Error>
97 enumeration or drawn from the BIB-1 diagnostic set.
98
99 =head2 ZOOM::diag_srw_str()
100
101  $msg = ZOOM::diag_srw_str(18);
102
103 Returns a human-readable English-language string corresponding to the
104 specified SRW error code.
105
106 =head2 ZOOM::event_str()
107
108  $msg = ZOOM::event_str(ZOOM::Event::RECV_APDU);
109
110 Returns a human-readable English-language string corresponding to the
111 event code that is its own parameter.  This works for any value of the
112 C<ZOOM::Event> enumeration.
113
114 =head2 ZOOM::event()
115
116  $connsRef = [ $conn1, $conn2, $conn3 ];
117  $which = ZOOM::event($connsRef);
118  $ev = $connsRef->[$which-1]->last_event()
119      if ($which != 0);
120
121 Used only in complex asynchronous applications, this function takes a
122 reference to a list of Connection objects, waits until an event
123 occurs on any one of them, and returns an integer indicating which of
124 the connections it occurred on.  The return value is a 1-based index
125 into the list; 0 is returned if no event occurs within the longest
126 timeout specified by the C<timeout> options of all the connections.
127
128 See the section below on asynchronous applications.
129
130 =head1 CLASSES
131
132 The eight ZOOM classes are described here in ``sensible order'':
133 first, the four commonly used classes, in the he order that they will
134 tend to be used in most programs (Connection, ResultSet, Record,
135 Exception); then the four more esoteric classes in descending order of
136 how often they are needed.
137
138 With the exception of the Options class, which is an extension to the
139 ZOOM model, the introduction to each class includes a link to the
140 relevant section of the ZOOM Abstract API.
141
142 =head2 ZOOM::Connection
143
144  $conn = new ZOOM::Connection("indexdata.dk:210/gils");
145  print("server is '", $conn->option("serverImplementationName"), "'\n");
146  $conn->option(preferredRecordSyntax => "usmarc");
147  $rs = $conn->search_pqf('@attr 1=4 mineral');
148  $ss = $conn->scan('@attr 1=1003 a');
149  if ($conn->errcode() != 0) {
150     die("somthing went wrong: " . $conn->errmsg())
151  }
152  $conn->destroy()
153
154 This class represents a connection to an information retrieval server,
155 using an IR protocol such as ANSI/NISO Z39.50, SRW (the
156 Search/Retrieve Webservice), SRU (the Search/Retrieve URL) or
157 OpenSearch.  Not all of these protocols require a low-level connection
158 to be maintained, but the Connection object nevertheless provides a
159 location for the necessary cache of configuration and state
160 information, as well as a uniform API to the connection-oriented
161 facilities (searching, index browsing, etc.), provided by these
162 protocols.
163
164 See the description of the C<Connection> class in the ZOOM Abstract
165 API at
166 http://zoom.z3950.org/api/zoom-current.html#3.2
167
168 =head3 Methods
169
170 =head4 new()
171
172  $conn = new ZOOM::Connection("indexdata.dk", 210);
173  $conn = new ZOOM::Connection("indexdata.dk:210/gils");
174  $conn = new ZOOM::Connection("tcp:indexdata.dk:210/gils");
175  $conn = new ZOOM::Connection("http:indexdata.dk:210/gils");
176  $conn = new ZOOM::Connection("indexdata.dk", 210,
177                                databaseName => "mydb",
178                                preferredRecordSyntax => "marc");
179
180 Creates a new Connection object, and immediately connects it to the
181 specified server.  If you want to make a new Connection object but
182 delay forging the connection, use the C<create()> and C<connect()>
183 methods instead.
184
185 This constructor can be called with two arguments or a single
186 argument.  In the former case, the arguments are the name and port
187 number of the Z39.50 server to connect to; in the latter case, the
188 single argument is a YAZ service-specifier string of the form
189
190 When the two-option form is used (which may be done using a vacuous
191 second argument of zero), any number of additional argument pairs may
192 be provided, which are interpreted as key-value pairs to be set as
193 options after the Connection object is created but before it is
194 connected to the server.  This is a convenient way to set options,
195 including those that must be set before connecting such as
196 authentication tokens.
197
198 The server-name string is of the form:
199
200 =over 4
201
202 =item
203
204 [I<scheme>:]I<host>[:I<port>][/I<databaseName>]
205
206 =back
207
208 In which the I<host> and I<port> parts are as in the two-argument
209 form, the I<databaseName> if provided specifies the name of the
210 database to be used in subsequent searches on this connection, and the
211 optional I<scheme> (default C<tcp>) indicates what protocol should be
212 used.  At present, the following schemes are supported:
213
214 =over 4
215
216 =item tcp
217
218 Z39.50 connection.
219
220 =item ssl
221
222 Z39.50 connection encrypted using SSL (Secure Sockets Layer).  Not
223 many servers support this, but Index Data's Zebra is one that does.
224
225 =item unix
226
227 Z39.50 connection on a Unix-domain (local) socket, in which case the
228 I<hostname> portion of the string is instead used as a filename in the
229 local filesystem.
230
231 =item http
232
233 SRU connection over HTTP.
234
235 =back
236
237 If the C<http> scheme is used, the particular SRU flavour to be used
238 may be specified by the C<sru> option, which takes the following
239 values:
240
241 =over 4
242
243 =item soap
244
245 SRU over SOAP (i.e. what used to be called SRW).
246 This is the default.
247
248 =item get
249
250 "SRU Classic" (i.e. SRU over HTTP GET).
251
252 =item post
253
254 SRU over HTTP POST.
255
256 =back
257
258 If an error occurs, an exception is thrown.  This may indicate a
259 networking problem (e.g. the host is not found or unreachable), or a
260 protocol-level problem (e.g. a Z39.50 server rejected the Init
261 request).
262
263 =head4 create() / connect()
264
265  $options = new ZOOM::Options();
266  $options->option(implementationName => "my client");
267  $options->option(implementationId => 12345);
268  $conn = create ZOOM::Connection($options)
269  # or
270  $conn = create ZOOM::Connection(implementationName => "my client",
271                                  implementationId => 12345);
272
273  $conn->connect($host, 0);
274
275 The usual Connection constructor, C<new()> brings a new object into
276 existence and forges the connection to the server all in one
277 operation, which is often what you want.  For applications that need
278 more control, however, these two methods separate the two steps,
279 allowing additional steps in between such as the setting of options.
280
281 C<create()> creates and returns a new Connection object, which is
282 I<not> connected to any server.  It may be passed an options block, of
283 type C<ZOOM::Options> (see below), into which options may be set
284 before or after the creation of the Connection.  Alternatively and
285 equivalently, C<create()> may be passed a list of key-value option
286 pairs directly.  The connection to the server may then be forged by
287 the C<connect()> method, which accepts hostname and port arguments
288 like those of the C<new()> constructor.
289
290 =head4 error_x() / errcode() / errmsg() / addinfo() / diagset()
291
292  ($errcode, $errmsg, $addinfo, $diagset) = $conn->error_x();
293  $errcode = $conn->errcode();
294  $errmsg = $conn->errmsg();
295  $addinfo = $conn->addinfo();
296  $diagset = $conn->diagset();
297
298 These methods may be used to obtain information about the last error
299 to have occurred on a connection - although typically they will not
300 been used, as the same information is available through the
301 C<ZOOM::Exception> that is thrown when the error occurs.  The
302 C<errcode()>,
303 C<errmsg()>,
304 C<addinfo()>
305 and
306 C<diagset()>
307 methods each return one element of the diagnostic, and
308 C<error_x()>
309 returns all four at once.
310
311 See the C<ZOOM::Exception> for the interpretation of these elements.
312
313 =head4 exception()
314
315  die $conn->exception();
316
317 C<exception()> returns the same information as C<error_x()> in the
318 form of a C<ZOOM::Exception> object which may be thrown or rendered.
319 If no error occurred on the connection, then C<exception()> returns an
320 undefined value.
321
322 =head4 check()
323
324  $conn->check();
325
326 Checks whether an error is pending on the connection, and throw a
327 C<ZOOM::Exception> object if so.  Since errors are thrown as they
328 occur for synchronous connections, there is no need ever to call this
329 except in asynchronous applications.
330
331 =head4 option() / option_binary()
332
333  print("server is '", $conn->option("serverImplementationName"), "'\n");
334  $conn->option(preferredRecordSyntax => "usmarc");
335  $conn->option_binary(iconBlob => "foo\0bar");
336  die if length($conn->option_binary("iconBlob") != 7);
337
338 Objects of the Connection, ResultSet, ScanSet and Package classes
339 carry with them a set of named options which affect their behaviour in
340 certain ways.  See the ZOOM-C options documentation for details:
341
342 Connection options are listed at
343 http://indexdata.com/yaz/doc/zoom.tkl#zoom.connections
344
345 These options are set and fetched using the C<option()> method, which
346 may be called with either one or two arguments.  In the two-argument
347 form, the option named by the first argument is set to the value of
348 the second argument, and its old value is returned.  In the
349 one-argument form, the value of the specified option is returned.
350
351 For historical reasons, option values are not binary-clean, so that a
352 value containing a NUL byte will be returned in truncated form.  The
353 C<option_binary()> method behaves identically to C<option()> except
354 that it is binary-clean, so that values containing NUL bytes are set
355 and returned correctly.
356
357 =head4 search() / search_pqf()
358
359  $rs = $conn->search(new ZOOM::Query::CQL('title=dinosaur'));
360  # The next two lines are equivalent
361  $rs = $conn->search(new ZOOM::Query::PQF('@attr 1=4 dinosaur'));
362  $rs = $conn->search_pqf('@attr 1=4 dinosaur');
363
364 The principal purpose of a search-and-retrieve protocol is searching
365 (and, er, retrieval), so the principal method used on a Connection
366 object is C<search()>.  It accepts a single argument, a C<ZOOM::Query>
367 object (or, more precisely, an object of a subclass of this class);
368 and it creates and returns a new ResultSet object representing the set
369 of records resulting from the search.
370
371 Since queries using PQF (Prefix Query Format) are so common, we make
372 them a special case by providing a C<search_pqf()> method.  This is
373 identical to C<search()> except that it accepts a string containing
374 the query rather than an object, thereby obviating the need to create
375 a C<ZOOM::Query::PQF> object.  See the documentation of that class for
376 information about PQF.
377
378 =head4 scan() / scan_pqf()
379
380  $rs = $conn->scan(new ZOOM::Query::CQL('title=dinosaur'));
381  # The next two lines are equivalent
382  $rs = $conn->scan(new ZOOM::Query::PQF('@attr 1=4 dinosaur'));
383  $rs = $conn->scan_pqf('@attr 1=4 dinosaur');
384
385 Many Z39.50 servers allow you to browse their indexes to find terms to
386 search for.  This is done using the C<scan> method, which creates and
387 returns a new ScanSet object representing the set of terms resulting
388 from the scan.
389
390 C<scan()> takes a single argument, but it has to work hard: it
391 specifies both what index to scan for terms, and where in the index to
392 start scanning.  What's more, the specification of what index to scan
393 includes multiple facets, such as what database fields it's an index
394 of (author, subject, title, etc.) and whether to scan for whole fields
395 or single words (e.g. the title ``I<The Empire Strikes Back>'', or the
396 four words ``Back'', ``Empire'', ``Strikes'' and ``The'', interleaved
397 with words from other titles in the same index.
398
399 All of this is done by using a Query object representing a query of a
400 single term as the C<scan()> argument.  The attributes associated with
401 the term indicate which index is to be used, and the term itself
402 indicates the point in the index at which to start the scan.  For
403 example, if the argument is the query C<@attr 1=4 fish>, then
404
405 =over 4
406
407 =item @attr 1=4
408
409 This is the BIB-1 attribute with type 1 (meaning access-point, which
410 specifies an index), and type 4 (which means ``title'').  So the scan
411 is in the title index.
412
413 =item fish
414
415 Start the scan from the lexicographically earliest term that is equal
416 to or falls after ``fish''.
417
418 =back
419
420 The argument C<@attr 1=4 @attr 6=3 fish> would behave similarly; but
421 the BIB-1 attribute 6=3 mean completeness=``complete field'', so the
422 scan would be for complete titles rather than for words occurring in
423 titles.
424
425 This takes a bit of getting used to.
426
427 The behaviour is C<scan()> is affected by the following options, which
428 may be set on the Connection through which the scan is done:
429
430 =over 4
431
432 =item number [default: 10]
433
434 Indicates how many terms should be returned in the ScanSet.  The
435 number actually returned may be less, if the start-point is near the
436 end of the index, but will not be greater.
437
438 =item position [default: 1]
439
440 A 1-based index specifying where in the returned list of terms the
441 seed-term should appear.  By default it should be the first term
442 returned, but C<position> may be set, for example, to zero (requesting
443 the next terms I<after> the seed-term), or to the same value as
444 C<number> (requesting the index terms I<before> the seed term).
445
446 =item stepSize [default: 0]
447
448 An integer indicating how many indexed terms are to be skipped between
449 each one returned in the ScanSet.  By default, no terms are skipped,
450 but overriding this can be useful to get a high-level overview of the
451 index.
452
453 Since scans using PQF (Prefix Query Format) are so common, we make
454 them a special case by providing a C<scan_pqf()> method.  This is
455 identical to C<scan()> except that it accepts a string containing the
456 query rather than an object, thereby obviating the need to create a
457 C<ZOOM::Query::PQF> object.
458
459 =back
460
461 =head4 package()
462
463  $p = $conn->package();
464  $o = new ZOOM::Options();
465  $o->option(databaseName => "newdb");
466  $p = $conn->package($o);
467
468 Creates and returns a new C<ZOOM::Package>, to be used in invoking an
469 Extended Service.  An options block may optionally be passed in.  See
470 the C<ZOOM::Package> documentation.
471
472 =head4 last_event()
473
474  if ($conn->last_event() == ZOOM::Event::CONNECT) {
475      print "Connected!\n";
476  }
477
478 Returns a C<ZOOM::Event> enumerated value indicating the type of the
479 last event that occurred on the connection.  This is used only in
480 complex asynchronous applications - see the sections below on the
481 C<ZOOM::Event> enumeration and asynchronous applications.
482
483 =head4 destroy()
484
485  $conn->destroy()
486
487 Destroys a Connection object, tearing down any low-level connection
488 associated with it and freeing its resources.  It is an error to reuse
489 a Connection that has been C<destroy()>ed.
490
491 =head2 ZOOM::ResultSet
492
493  $rs = $conn->search_pqf('@attr 1=4 mineral');
494  $n = $rs->size();
495  for $i (1 .. $n) {
496      $rec = $rs->record($i-1);
497      print $rec->render();
498  }
499
500 A ResultSet object represents the set of zero or more records
501 resulting from a search, and is the means whereby these records can be
502 retrieved.  A ResultSet object may maintain client side cache or some,
503 less, none, all or more of the server's records: in general, this is
504 supposed to an implementaton detail of no interest to a typical
505 application, although more sophisticated applications do have
506 facilities for messing with the cache.  Most applications will only
507 need the C<size()>, C<record()> and C<sort()> methods.
508
509 There is no C<new()> method nor any other explicit constructor.  The
510 only way to create a new ResultSet is by using C<search()> (or
511 C<search_pqf()>) on a Connection.
512
513 See the description of the C<Result Set> class in the ZOOM Abstract
514 API at
515 http://zoom.z3950.org/api/zoom-current.html#3.4
516
517 =head3 Methods
518
519 =head4 option()
520
521  $rs->option(elementSetName => "f");
522
523 Allows options to be set into, and read from, a ResultSet, just like
524 the Connection class's C<option()> method.  There is no
525 C<option_binary()> method for ResultSet objects.
526
527 ResultSet options are listed at
528 http://indexdata.com/yaz/doc/zoom.resultsets.tkl
529
530 =head4 size()
531
532  print "Found ", $rs->size(), " records\n";
533
534 Returns the number of records in the result set.
535
536 =head4 record() / record_immediate()
537
538  $rec = $rs->record(0);
539  $rec2 = $rs->record_immediate(0);
540  $rec3 = $rs->record_immediate(1)
541      or print "second record wasn't in cache\n";
542
543 The C<record()> method returns a C<ZOOM::Record> object representing
544 a record from result-set, whose position is indicated by the argument
545 passed in.  This is a zero-based index, so that legitimate values
546 range from zero to C<$rs-E<gt>size()-1>.
547
548 The C<record_immediate()> API is identical, but it never invokes a
549 network operation, merely returning the record from the ResultSet's
550 cache if it's already there, or an undefined value otherwise.  So if
551 you use this method, B<you must always check the return value>.
552
553 =head4 records()
554
555  $rs->records(0, 10, 0);
556  for $i (0..10) {
557      print $rs->record_immediate($i)->render();
558  }
559
560  @nextseven = $rs->records(10, 7, 1);
561
562 The C<record_immediate()> method only fetches records from the cache,
563 whereas C<record()> fetches them from the server if they have not
564 already been cached; but the ZOOM module has to guess what the most
565 efficient strategy for this is.  It might fetch each record, alone
566 when asked for: that's optimal in an application that's only
567 interested in the top hit from each search, but pessimal for one that
568 wants to display a whole list of results.  Conversely, the software's
569 strategy might be always to ask for blocks of a twenty records:
570 that's great for assembling long lists of things, but wasteful when
571 only one record is wanted.  The problem is that the ZOOM module can't
572 tell, when you call C<$rs-E<gt>record()>, what your intention is.
573
574 But you can tell it.  The C<records()> method fetches a sequence of
575 records, all in one go.  It takes three arguments: the first is the
576 zero-based index of the first record in the sequence, the second is
577 the number of records to fetch, and the third is a boolean indication
578 of whether or not to return the retrieved records as well as adding
579 them to the cache.  (You can always pass 1 for this if you like, and
580 Perl will discard the unused return value, but there is a small
581 efficiency gain to be had by passing 0.)
582
583 Once the records have been retrieved from the server
584 (i.e. C<records()> has completed without throwing an exception), they
585 can be fetched much more efficiently using C<record()> - or
586 C<record_immediate()>, which is then guaranteed to succeed.
587
588 =head4 cache_reset()
589
590  $rs->cache_reset()
591
592 Resets the ResultSet's record cache, so that subsequent invocations of
593 C<record_immediate()> will fail.  I struggle to imagine a real
594 scenario where you'd want to do this.
595
596 =head4 sort()
597
598  if ($rs->sort("yaz", "1=4 >i 1=21 >s") < 0) {
599      die "sort failed";
600  }
601
602 Sorts the ResultSet in place (discarding any cached records, as they
603 will in general be sorted into a different position).  There are two
604 arguments: the first is a string indicating the type of the
605 sort-specification, and the second is the specification itself.
606
607 The C<sort()> method returns 0 on success, or -1 if the
608 sort-specification is invalid.
609
610 At present, the only supported sort-specification type is C<yaz>.
611 Such a specification consists of a space-separated sequence of keys,
612 each of which itself consists of two space-separated words (so that
613 the total number of words in the sort-specification is even).  The two
614 words making up each key are a field and a set of flags.  The field
615 can take one of two forms: if it contains an C<=> sign, then it is a
616 BIB-1 I<type>=I<value> pair specifying which field to sort
617 (e.g. C<1=4> for a title sort); otherwise it is sent for the server to
618 interpret as best it can.  The word of flags is made up from one or
619 more of the following: C<s> for case sensitive, C<i> for case
620 insensitive; C<<> for ascending order and C<E<gt>> for descending
621 order.
622
623 For example, the sort-specification in the code-fragment above will
624 sort the records in C<$rs> case-insensitively in descending order of
625 title, with records having equivalent titles sorted case-sensitively
626 in ascending order of subject.  (The BIB-1 access points 4 and 21
627 represent title and subject respectively.)
628  
629 =head4 destroy()
630
631  $rs->destroy()
632
633 Destroys a ResultSet object, freeing its resources.  It is an error to
634 reuse a ResultSet that has been C<destroy()>ed.
635
636 =head2 ZOOM::Record
637
638  $rec = $rs->record($i);
639  print $rec->render();
640  $raw = $rec->raw();
641  $marc = new_from_usmarc MARC::Record($raw);
642  print "Record title is: ", $marc->title(), "\n";
643
644 A Record object represents a record that has been retrived from the
645 server.
646
647 There is no C<new()> method nor any other explicit constructor.  The
648 only way to create a new Record is by using C<record()> (or
649 C<record_immediate()>, or C<records()>) on a ResultSet.
650
651 In general, records are ``owned'' by their result-sets that they were
652 retrieved from, so they do not have to be explicitly memory-managed:
653 they are deallocated (and therefore can no longer be used) when the
654 result-set is destroyed.
655
656 See the description of the C<Record> class in the ZOOM Abstract
657 API at
658 http://zoom.z3950.org/api/zoom-current.html#3.5
659
660 =head3 Methods
661
662 =head4 error() / exception()
663
664  if ($rec->error()) {
665      my($code, $msg, $addinfo, $dset) = $rec->error();
666      print "error $code, $msg ($addinfo) from $dset set\n";
667      die $rec->exception();
668  }
669
670 These functions test for surrogate diagnostics associated with a
671 record: that is, errors pertaining to a particular record rather than
672 to the fetch-some-records operation as a whole.  (The latter are known
673 in Z39.50 as non-surrogate diagnostics, and are reported as exceptions
674 thrown by searches.)  If a particular record can't be obtained - for
675 example, because it is not available in the requested record syntax -
676 then the record object obtained from the result-set, when interrogated
677 with these functions, will report the error.
678
679 C<error()> returns the error-code, a human-readable message,
680 additional information and the name of the diagnostic set that the
681 error is from.  When called in a scalar context, it just returns the
682 error-code.  Since error 0 means "no error", it can be used as a
683 boolean has-there-been-an-error indicator.
684
685 C<exception()> returns the same information in the form of a
686 C<ZOOM::Exception> object which may be thrown or rendered.  If no
687 error occurred on the record, then C<exception()> returns an undefined
688 value.
689
690 =head4 render()
691
692  print $rec->render();
693  print $rec->render("charset=latin1,utf8");
694
695 Returns a human-readable representation of the record.  Beyond that,
696 no promises are made: careful programs should not make assumptions
697 about the format of the returned string.
698
699 If the optional argument is provided, then it is interpreted as in the
700 C<get()> method (q.v.)
701
702 This method is useful mostly for debugging.
703
704 =head4 raw()
705
706  use MARC::Record;
707  $raw = $rec->raw();
708  $marc = new_from_usmarc MARC::Record($raw);
709  $trans = $rec->render("charset=latin1,utf8");
710
711 Returns an opaque blob of data that is the raw form of the record.
712 Exactly what this is, and what you can do with it, varies depending on
713 the record-syntax.  For example, XML records will be returned as,
714 well, XML; MARC records will be returned as ISO 2709-encoded blocks
715 that can be decoded by software such as the fine C<Marc::Record>
716 module; GRS-1 record will be ... gosh, what an interesting question.
717 But no-one uses GRS-1 any more, do they?
718
719 If the optional argument is provided, then it is interpreted as in the
720 C<get()> method (q.v.)
721
722 =head4 get()
723
724  $raw = $rec->get("raw");
725  $rendered = $rec->get("render");
726  $trans = $rec->get("render;charset=latin1,utf8");
727  $trans = $rec->get("render", "charset=latin1,utf8");
728
729 This is the underlying method used by C<render()> and C<raw()>, and
730 which in turn delegates to the C<ZOOM_record_get()> function of the
731 underlying ZOOM-C library.  Most applications will find it more
732 natural to work with C<render()> and C<raw()>.
733
734 C<get()> may be called with either one or two arguments.  The
735 two-argument form is syntactic sugar: the two arguments are simply
736 joined with a semi-colon to make a single argument, so the third and
737 fourth example invocations above are equivalent.  The second argument
738 (or portion of the first argument following the semicolon) is used in
739 the C<type> argument of C<ZOOM_record_get()>, as described in
740 http://www.indexdata.com/yaz/doc/zoom.records.tkl
741 This is useful primarily for invoking the character-set transformation
742 - in the examples above, from ISO Latin-1 to UTF-8 Unicode.
743
744 =head4 clone() / destroy()
745
746  $rec = $rs->record($i);
747  $newrec = $rec->clone();
748  $rs->destroy();
749  print $newrec->render();
750  $newrec->destroy();
751
752 Usually, it's convenient that Record objects are owned by their
753 ResultSets and go away when the ResultSet is destroyed; but
754 occasionally you need a Record to outlive its parent and destroy it
755 later, explicitly.  To do this, C<clone()> the record, keep the new
756 Record object that is returned, and C<destroy()> it when it's no
757 longer needed.  This is B<only> situation in which a Record needs to
758 be destroyed.
759
760 =head2 ZOOM::Exception
761
762 In general, method calls throw an exception (of class
763 C<ZOOM::Exception>) if anything goes wrong, so you don't need to test
764 for success after each call.  Exceptions are caught by enclosing the
765 main code in an C<eval{}> block and checking C<$@> on exit from that
766 block, as in the code-sample above.
767
768 There are a small number of exceptions to this rule: the three
769 record-fetching methods in the C<ZOOM::ResultSet> class,
770 C<record()>,
771 C<record_immediate()>,
772 and
773 C<records()>
774 can all return undefined values for legitimate reasons, under
775 circumstances that do not merit throwing an exception.  For this
776 reason, the return values of these methods should be checked.  See the
777 individual methods' documentation for details.
778
779 An exception carries the following pieces of information:
780
781 =over 4
782
783 =item error-code
784
785 A numeric code that specifies the type of error.  This can be checked
786 for equality with known values, so that intelligent applications can
787 take appropriate action.
788
789 =item error-message
790
791 A human-readable message corresponding with the code.  This can be
792 shown to users, but its value should not be tested, as it could vary
793 in different versions or under different locales.
794
795 =item additional information [optional]
796
797 A string containing information specific to the error-code.  For
798 example, when the error-code is the BIB-1 diagnostic 109 ("Database
799 unavailable"), the additional information is the name of the database
800 that the application tried to use.  For some error-codes, there is no
801 additional information at all; for some others, the additional
802 information is undefined and may just be an human-readable string.
803
804 =item diagnostic set [optional]
805
806 A short string specifying the diagnostic set from which the error-code
807 was drawn: for example, C<ZOOM> for a ZOOM-specific error such as
808 C<ZOOM::Error::MEMORY> ("out of memory"), and C<BIB-1> for a Z39.50
809 error-code drawn from the BIB-1 diagnostic set.
810
811 =back
812
813 In theory, the error-code should be interpreted in the context of the
814 diagnostic set from which it is drawn; in practice, nearly all errors
815 are from either the ZOOM or BIB-1 diagnostic sets, and the codes in
816 those sets have been chosen so as not to overlap, so the diagnostic
817 set can usually be ignored.
818
819 See the description of the C<Exception> class in the ZOOM Abstract
820 API at
821 http://zoom.z3950.org/api/zoom-current.html#3.7
822
823 =head3 Methods
824
825 =head4 new()
826
827  die new ZOOM::Exception($errcode, $errmsg, $addinfo, $diagset);
828
829 Creates and returns a new Exception object with the specified
830 error-code, error-message, additional information and diagnostic set.
831 Applications will not in general need to use this, but may find it
832 useful to simulate ZOOM exceptions.  As is usual with Perl, exceptions
833 are thrown using C<die()>.
834
835 =head4 code() / message() / addinfo() / diagset()
836
837  print "Error ", $@->code(), ": ", $@->message(), "\n";
838  print "(addinfo '", $@->addinfo(), "', set '", $@->diagset(), "')\n";
839
840 These methods, of no arguments, return the exception's error-code,
841 error-message, additional information and diagnostic set respectively.
842
843 =head4 render()
844
845  print $@->render();
846
847 Returns a human-readable rendition of an exception.  The C<"">
848 operator is overloaded on the Exception class, so that an Exception
849 used in a string context is automatically rendered.  Among other
850 consequences, this has the useful result that a ZOOM application that
851 died due to an uncaught exception will emit an informative message
852 before exiting.
853
854 =head2 ZOOM::ScanSet
855
856  $ss = $conn->scan('@attr 1=1003 a');
857  $n = $ss->size();
858  ($term, $occ) = $ss->term($n-1);
859  $rs = $conn->search_pqf('@attr 1=1003 "' . $term . "'");
860  assert($rs->size() == $occ);
861
862 A ScanSet represents a set of candidate search-terms returned from an
863 index scan.  Its sole purpose is to provide access to those term, to
864 the corresponding display terms, and to the occurrence-counts of the
865 terms.
866
867 There is no C<new()> method nor any other explicit constructor.  The
868 only way to create a new ScanSet is by using C<scan()> on a
869 Connection.
870
871 See the description of the C<Scan Set> class in the ZOOM Abstract
872 API at
873 http://zoom.z3950.org/api/zoom-current.html#3.6
874
875 =head3 Methods
876
877 =head4 size()
878
879  print "Found ", $ss->size(), " terms\n";
880
881 Returns the number of terms in the scan set.  In general, this will be
882 the scan-set size requested by the C<number> option in the Connection
883 on which the scan was performed [default 10], but it may be fewer if
884 the scan is close to the end of the index.
885
886 =head4 term() / display_term()
887
888  $ss = $conn->scan('@attr 1=1004 whatever');
889  ($term, $occurrences) = $ss->term(0);
890  ($displayTerm, $occurrences2) = $ss->display_term(0);
891  assert($occurrences == $occurrences2);
892  if (user_likes_the_look_of($displayTerm)) {
893      $rs = $conn->search_pqf('@attr 1=4 "' . $term . '"');
894      assert($rs->size() == $occurrences);
895  }
896
897 These methods return the scanned terms themselves.  C<term()> returns
898 the term is a form suitable for submitting as part of a query, whereas
899 C<display_term()> returns it in a form suitable for displaying to a
900 user.  Both versions also return the number of occurrences of the term
901 in the index, i.e. the number of hits that will be found if the term
902 is subsequently used in a query.
903
904 In most cases, the term and display term will be identical; however,
905 they may be different in cases where punctuation or case is
906 normalised, or where identifiers rather than the original document
907 terms are indexed.
908
909 =head4 option()
910
911  print "scan status is ", $ss->option("scanStatus");
912
913 Allows options to be set into, and read from, a ScanSet, just like
914 the Connection class's C<option()> method.  There is no
915 C<option_binary()> method for ScanSet objects.
916
917 ScanSet options are also described, though not particularly
918 informatively, at
919 http://indexdata.com/yaz/doc/zoom.scan.tkl
920
921 =head4 destroy()
922
923  $ss->destroy()
924
925 Destroys a ScanSet object, freeing its resources.  It is an error to
926 reuse a ScanSet that has been C<destroy()>ed.
927
928 =head2 ZOOM::Package
929
930  $p = $conn->package();
931  $p->option(action => "specialUpdate");
932  $p->option(recordIdOpaque => 145);
933  $p->option(record => content_of("/tmp/record.xml"));
934  $p->send("update");
935  $p->destroy();
936
937 This class represents an Extended Services Package: an instruction to
938 the server to do something not covered by the core parts of the Z39.50
939 standard (or the equivalent in SRW or SRU).  Since the core protocols
940 are read-only, such requests are often used to make changes to the
941 database, such as in the record update example above.
942
943 Requesting an extended service is a four-step process: first, create a
944 package associated with the connection to the relevant database;
945 second, set options on the package to instruct the server on what to
946 do; third, send the package (which may result in an exception being
947 thrown if the server cannot execute the requested operations; and
948 finally, destroy the package.
949
950 Package options are listed at
951 http://indexdata.com/yaz/doc/zoom.ext.tkl
952
953 The particular options that have meaning are determined by the
954 top-level operation string specified as the argument to C<send()>.
955 For example, when the operation is C<update> (the most commonly used
956 extended service), the C<action> option may be set to any of
957 C<recordInsert>
958 (add a new record, failing if that record already exists),
959 C<recordDelete>
960 (delete a record, failing if it is not in the database).
961 C<recordReplace>
962 (replace a record, failing if an old version is not already present)
963 or
964 C<specialUpdate>
965 (add a record, replacing any existing version that may be present).
966
967 For update, the C<record> option should be set to the full text of the
968 XML record to added, deleted or replaced.  Depending on how the server
969 is configured, it may extract the record's unique ID from the text
970 (i.e. from a known element such as the C<001> field of a MARCXML
971 record), or it may require the unique ID to passed in explicitly using
972 the C<recordIdOpaque> option.
973
974 Extended services packages are B<not currently described> in the ZOOM
975 Abstract API at
976 http://zoom.z3950.org/api/zoom-current.html
977 They will be added in a forthcoming version, and will function much
978 as those implemented in this module.
979
980 =head3 Methods
981
982 =head4 option()
983
984  $p->option(recordIdOpaque => "46696f6e61");
985
986 Allows options to be set into, and read from, a Package, just like
987 the Connection class's C<option()> method.  There is no
988 C<option_binary()> method for Package objects.
989
990 Package options are listed at
991 http://indexdata.com/yaz/doc/zoom.ext.tkl
992
993 =head4 send()
994
995  $p->send("create");
996
997 Sends a package to the server associated with the Connection that
998 created it.  Problems are reported by throwing an exception.  The
999 single parameter indicates the operation that the server is being
1000 requested to perform, and controls the interpretation of the package's
1001 options.  Valid operations include:
1002
1003 =over 4
1004
1005 =item itemorder
1006
1007 Request a copy of a nominated object, e.g. place an ILL request.
1008
1009 =item create
1010
1011 Create a new database, the name of which is specified by the
1012 C<databaseName> option.
1013
1014 =item drop
1015
1016 Drop an existing database, the name of which is specified by the
1017 C<databaseName> option.
1018
1019 =item commit
1020
1021 Commit changes made to the database within a transaction.
1022
1023 =item update
1024
1025 Modify the contents of the database by adding, deleting or replacing
1026 records (as described above in the overview of the C<ZOOM::Package>
1027 class).
1028
1029 =item xmlupdate
1030
1031 I have no idea what this does.
1032
1033 =back
1034
1035 Although the module is capable of I<making> all these requests, not
1036 all servers are capable of I<executing> them.  Refusal is indicated by
1037 throwing an exception.  Problems may also be caused by lack of
1038 privileges; so C<send()> must be used with caution, and is perhaps
1039 best wrapped in a clause that checks for execptions, like so:
1040
1041  eval { $p->send("create") };
1042  if ($@ && $@->isa("ZOOM::Exception")) {
1043      print "Oops!  ", $@->message(), "\n";
1044      return $@->code();
1045  }
1046
1047 =head4 destroy()
1048
1049  $p->destroy()
1050
1051 Destroys a Package object, freeing its resources.  It is an error to
1052 reuse a Package that has been C<destroy()>ed.
1053
1054 =head2 ZOOM::Query
1055
1056  $q = new ZOOM::Query::CQL("creator=pike and subject=unix");
1057  $q->sortby("1=4 >i 1=21 >s");
1058  $rs = $conn->search($q);
1059  $q->destroy();
1060
1061 C<ZOOM::Query> is a virtual base class from which various concrete
1062 subclasses can be derived.  Different subclasses implement different
1063 types of query.  The sole purpose of a Query object is to be used in a
1064 C<search()> on a Connection; because PQF is such a common special
1065 case, the shortcut Connection method C<search_pqf()> is provided.
1066
1067 The following Query subclasses are provided, each providing the
1068 same set of methods described below:
1069
1070 =over 4
1071
1072 =item ZOOM::Query::PQF
1073
1074 Implements Prefix Query Format (PQF), also sometimes known as Prefix
1075 Query Notation (PQN).  This esoteric but rigorous and expressive
1076 format is described in the YAZ Manual at
1077 http://indexdata.com/yaz/doc/tools.tkl#PQF
1078
1079 =item ZOOM::Query::CQL
1080
1081 Implements the Common Query Language (CQL) of SRU, the Search/Retrieve
1082 URL.  CQL is a much friendlier notation than PQF, using a simple infix
1083 notation.  The queries are passed ``as is'' to the server rather than
1084 being compiled into a Z39.50 Type-1 query, so only CQL-compliant
1085 servers can support such querier.  CQL is described at
1086 http://www.loc.gov/standards/sru/cql/
1087 and in a slight out-of-date but nevertheless useful tutorial at
1088 http://zing.z3950.org/cql/intro.html
1089
1090 =item ZOOM::Query::CQL2RPN
1091
1092 Implements CQL by compiling it on the client-side into a Z39.50
1093 Type-1 (RPN) query, and sending that.  This provides essentially the
1094 same functionality as C<ZOOM::Query::CQL>, but it will work against
1095 any standard Z39.50 server rather than only against the small subset
1096 that support CQL natively.  The drawback is that, because the
1097 compilation is done on the client side, a configuration file is
1098 required to direct the mapping of CQL constructs such as index names,
1099 relations and modifiers into Type-1 query attributes.  An example CQL
1100 configuration file is included in the ZOOM-Perl distribution, in the
1101 file C<samples/cql/pqf.properties>
1102
1103 =item ZOOM::Query::CCL2RPN
1104
1105 Implements CCL by compiling it on the client-side into a Z39.50 Type-1
1106 (RPN) query, and sending that.  Because the compilation is done on the
1107 client side, a configuration file is required to direct the mapping of
1108 CCL constructs such as index names and boolean operators into Type-1
1109 query attributes.  An example CCL configuration file is included in
1110 the ZOOM-Perl distribution, in the file C<samples/ccl/default.bib>
1111
1112 CCL is syntactically very similar to CQL, but much looser.  While CQL
1113 is an entirely precise language in which each possible query has
1114 rigorously defined semantics, and is thus suitable for transfer as
1115 part of a protocol, CCL is best deployed as a human-facing UI
1116 language.
1117
1118 =back
1119
1120 See the description of the C<Query> class in the ZOOM Abstract
1121 API at
1122 http://zoom.z3950.org/api/zoom-current.html#3.3
1123
1124 =head3 Methods
1125
1126 =head4 new()
1127
1128  $q = new ZOOM::Query::CQL('title=dinosaur');
1129  $q = new ZOOM::Query::PQF('@attr 1=4 dinosaur');
1130
1131 Creates a new query object, compiling the query passed as its argument
1132 according to the rules of the particular query-type being
1133 instantiated.  If compilation fails, an exception is thrown.
1134 Otherwise, the query may be passed to the C<Connection> method
1135 C<search()>.
1136
1137  $conn->option(cqlfile => "samples/cql/pqf.properties");
1138  $q = new ZOOM::Query::CQL2RPN('title=dinosaur', $conn);
1139
1140 Note that for the C<ZOOM::Query::CQL2RPN> subclass, the Connection
1141 must also be passed into the constructor.  This is used for two
1142 purposes: first, its C<cqlfile> option is used to find the CQL
1143 configuration file that directs the translations into RPN; and second,
1144 if compilation fails, then diagnostic information is cached in the
1145 Connection and be retrieved using C<$conn-E<gt>errcode()> and related
1146 methods.
1147
1148  $conn->option(cclfile => "samples/ccl/default.bib");
1149  # or
1150  $conn->option(cclqual => "ti u=4 s=pw\nab u=62 s=pw");
1151  $q = new ZOOM::Query::CCL2RPN('ti=dinosaur', $conn);
1152
1153 For the C<ZOOM::Query::CCL2RPN> subclass, too, the Connection must be
1154 passed into the constructor, for the same reasons as when client-side
1155 CQL compilation is used.  The C<cclqual> option, if defined, gives a
1156 CCL qualification specification inline; otherwise, the contents of the
1157 file named by the C<cclfile> option are used.
1158
1159 =head4 sortby()
1160
1161  $q->sortby("1=4 >i 1=21 >s");
1162
1163 Sets a sort specification into the query, so that when a C<search()>
1164 is run on the query, the result is automatically sorted.  The sort
1165 specification language is the same as the C<yaz> sort-specification
1166 type of the C<ResultSet> method C<sort()>, described above.
1167
1168 =head4 destroy()
1169
1170  $p->destroy()
1171
1172 Destroys a Query object, freeing its resources.  It is an error to
1173 reuse a Query that has been C<destroy()>ed.
1174
1175 =head2 ZOOM::Options
1176
1177  $o1 = new ZOOM::Options();
1178  $o1->option(user => "alf");
1179  $o2 = new ZOOM::Options();
1180  $o2->option(password => "fruit");
1181  $opts = new ZOOM::Options($o1, $o2);
1182  $conn = create ZOOM::Connection($opts);
1183  $conn->connect($host); # Uses the specified username and password
1184
1185 Several classes of ZOOM objects carry their own sets of options, which
1186 can be manipulated using their C<option()> method.  Sometimes,
1187 however, it's useful to deal with the option sets directly, and the
1188 C<ZOOM::Options> class exists to enable this approach.
1189
1190 Option sets are B<not currently described> in the ZOOM
1191 Abstract API at
1192 http://zoom.z3950.org/api/zoom-current.html
1193 They are an extension to that specification.
1194
1195 =head3 Methods
1196
1197 =head4 new()
1198
1199  $o1 = new ZOOM::Options();
1200  $o1and2 = new ZOOM::Options($o1);
1201  $o3 = new ZOOM::Options();
1202  $o1and3and4 = new ZOOM::Options($o1, $o3);
1203
1204 Creates and returns a new option set.  One or two (but no more)
1205 existing option sets may be passed as arguments, in which case they
1206 become ``parents'' of the new set, which thereby ``inherits'' their
1207 options, the values of the first parent overriding those of the second
1208 when both have a value for the same key.  An option set that inherits
1209 from a parent that has its own parents also inherits the grandparent's
1210 options, and so on.
1211
1212 =head4 option() / option_binary()
1213
1214  $o->option(preferredRecordSyntax => "usmarc");
1215  $o->option_binary(iconBlob => "foo\0bar");
1216  die if length($o->option_binary("iconBlob") != 7);
1217
1218 These methods are used to get and set options within a set, and behave
1219 the same way as the same-named C<Connection> methods - see above.  As
1220 with the C<Connection> methods, values passed to and retrieved using
1221 C<option()> are interpreted as NUL-terminated, while those passed to
1222 and retrieved from C<option_binary()> are binary-clean.
1223
1224 =head4 bool()
1225
1226  $o->option(x => "T");
1227  $o->option(y => "F");
1228  assert($o->bool("x", 1));
1229  assert(!$o->bool("y", 1));
1230  assert($o->bool("z", 1));
1231
1232 The first argument is a key, and the second is a default value.
1233 Returns the value associated with the specified key as a boolean, or
1234 the default value if the key has not been set.  The values C<T> (upper
1235 case) and C<1> are considered true; all other values (including C<t>
1236 (lower case) and non-zero integers other than one) are considered
1237 false.
1238
1239 This method is provided in ZOOM-C because in a statically typed
1240 language it's convenient to have the result returned as an
1241 easy-to-test type.  In a dynamically typed language such as Perl, this
1242 problem doesn't arise, so C<bool()> is nearly useless; but it is made
1243 available in case applications need to duplicate the idiosyncratic
1244 interpretation of truth and falsehood and ZOOM-C uses.
1245
1246 =head4 int()
1247
1248  $o->option(x => "012");
1249  assert($o->int("x", 20) == 12);
1250  assert($o->int("y", 20) == 20);
1251
1252 Returns the value associated with the specified key as an integer, or
1253 the default value if the key has not been set.  See the description of
1254 C<bool()> for why you almost certainly don't want to use this.
1255
1256 =head4 set_int()
1257
1258  $o->set_int(x => "29");
1259
1260 Sets the value of the specified option as an integer.  Of course, Perl
1261 happily converts strings to integers on its own, so you can just use
1262 C<option()> for this, but C<set_int()> is guaranteed to use the same
1263 string-to-integer conversion as ZOOM-C does, which might occasionally
1264 be useful.  Though I can't imagine how.
1265
1266 =head4 set_callback()
1267
1268  sub cb {
1269      ($udata, $key) = @;
1270      return "$udata-$key-$udata";
1271  }
1272  $o->set_callback(\&cb, "xyz");
1273  assert($o->option("foo") eq "xyz-foo-xyz");
1274
1275 This method allows a callback function to be installed in an option
1276 set, so that the values of options can be calculated algorithmically
1277 rather than, as usual, looked up in a table.  Along with the callback
1278 function itself, an additional datum is provided: when an option is
1279 subsequently looked up, this datum is passed to the callback function
1280 along with the key; and its return value is returned to the caller as
1281 the value of the option.
1282
1283 B<Warning.>
1284 Although it ought to be possible to specify callback function using
1285 the C<\&name> syntax above, or a literal C<sub { code }> code
1286 reference, the complexities of the Perl-internal memory management
1287 system mean that the function must currently be specified as a string
1288 containing the fully-qualified name, e.g. C<"main::cb">.>
1289
1290 B<Warning.>
1291 The current implementation of the this method leaks memory, not only
1292 when the callback is installed, but on every occasion that it is
1293 consulted to look up an option value.
1294
1295 =head4 destroy()
1296
1297  $o->destroy()
1298
1299 Destroys an Options object, freeing its resources.  It is an error to
1300 reuse an Options object that has been C<destroy()>ed.
1301
1302 =head1 ENUMERATIONS
1303
1304 The ZOOM module provides two enumerations that list possible return
1305 values from particular functions.  They are described in the following
1306 sections.
1307
1308 =head2 ZOOM::Error
1309
1310  if ($@->code() == ZOOM::Error::QUERY_PQF) {
1311      return "your query was not accepted";
1312  }
1313
1314 This class provides a set of manifest constants representing some of
1315 the possible error codes that can be raised by the ZOOM module.  The
1316 methods that return error-codes are
1317 C<ZOOM::Exception::code()>,
1318 C<ZOOM::Connection::error_x()>
1319 and
1320 C<ZOOM::Connection::errcode()>.
1321
1322 The C<ZOOM::Error> class provides the constants
1323 C<NONE>,
1324 C<CONNECT>,
1325 C<MEMORY>,
1326 C<ENCODE>,
1327 C<DECODE>,
1328 C<CONNECTION_LOST>,
1329 C<ZINIT>,
1330 C<INTERNAL>,
1331 C<TIMEOUT>,
1332 C<UNSUPPORTED_PROTOCOL>,
1333 C<UNSUPPORTED_QUERY>,
1334 C<INVALID_QUERY>,
1335 C<CQL_PARSE>,
1336 C<CQL_TRANSFORM>,
1337 C<CCL_CONFIG>,
1338 C<CCL_PARSE>,
1339 C<CREATE_QUERY>,
1340 C<QUERY_CQL>,
1341 C<QUERY_PQF>,
1342 C<SORTBY>,
1343 C<CLONE>,
1344 C<PACKAGE>,
1345 C<SCANTERM>
1346 and
1347 C<LOGLEVEL>,
1348 each of which specifies a client-side error.  These codes constitute
1349 the C<ZOOM> diagnostic set.
1350
1351 Since errors may also be diagnosed by the server, and returned to the
1352 client, error codes may also take values from the BIB-1 diagnostic set
1353 of Z39.50, listed at the Z39.50 Maintenance Agency's web-site at
1354 http://www.loc.gov/z3950/agency/defns/bib1diag.html
1355
1356 All error-codes, whether client-side from the C<ZOOM::Error>
1357 enumeration or server-side from the BIB-1 diagnostic set, can be
1358 translated into human-readable messages by passing them to the
1359 C<ZOOM::diag_str()> utility function.
1360
1361 =head2 ZOOM::Event
1362
1363  if ($conn->last_event() == ZOOM::Event::CONNECT) {
1364      print "Connected!\n";
1365  }
1366
1367 In applications that need it - mostly complex multiplexing
1368 applications - The C<ZOOM::Connection::last_event()> method is used to
1369 return an indication of the last event that occurred on a particular
1370 connection.  It always returns a value drawn from this enumeration,
1371 that is, one of C<NONE>, C<CONNECT>, C<SEND_DATA>, C<RECV_DATA>,
1372 C<TIMEOUT>, C<UNKNOWN>, C<SEND_APDU>, C<RECV_APDU>, C<RECV_RECORD>,
1373 C<RECV_SEARCH> or C<ZEND>.
1374
1375 See the section below on asynchronous applications.
1376
1377 =head1 LOGGING
1378
1379  ZOOM::Log::init_level(ZOOM::Log::mask_str("zoom,myapp,-warn"));
1380  ZOOM::Log::log("myapp", "starting up with pid ", $$);
1381
1382 Logging facilities are provided by a set of functions in the
1383 C<ZOOM::Log> module.  Note that C<ZOOM::Log> is not a class, and it
1384 is not possible to create C<ZOOM::Log> objects: the API is imperative,
1385 reflecting that of the underlying YAZ logging facilities.  Although
1386 there are nine logging functions altogether, you can ignore nearly
1387 all of them: most applications that use logging will begin by calling
1388 C<mask_str()> and C<init_level()> once each, as above, and will then
1389 repeatedly call C<log()>.
1390
1391 =head2 mask_str()
1392
1393  $level = ZOOM::Log::mask_str("zoom,myapp,-warn");
1394
1395 Returns an integer corresponding to the log-level specified by the
1396 parameter.  This is a string of zero or more comma-separated
1397 module-names, each indicating an individual module to be either added
1398 to the default log-level or removed from it (for those components
1399 prefixed by a minus-sign).  The names may be those of either standard
1400 YAZ-logging modules such as C<fatal>, C<debug> and C<warn>, or custom
1401 modules such as C<myapp> in the example above.  The module C<zoom>
1402 requests logging from the ZOOM module itself, which may be helpful for
1403 debugging.
1404
1405 Note that calling this function does not in any way change the logging
1406 state: it merely returns a value.  To change the state, this value
1407 must be passed to C<init_level()>.
1408
1409 =head2 module_level()
1410
1411  $level = ZOOM::Log::module_level("zoom");
1412  ZOOM::Log::log($level, "all systems clear: thrusters invogriated");
1413
1414 Returns the integer corresponding to the single log-level specified as
1415 the parameter, or zero if that level has not been registered by a
1416 prior call to C<mask_str()>.  Since C<log()> accepts either a numeric
1417 log-level or a string, there is no reason to call this function; but,
1418 what the heck, maybe you enjoy that kind of thing.  Who are we to
1419 judge?
1420
1421 =head2 init_level()
1422
1423  ZOOM::Log::init_level($level);
1424
1425 Initialises the log-level to the specified integer, which is a bitmask
1426 of values, typically as returned from C<mask_str()>.  All subsequent
1427 calls to C<log()> made with a log-level that matches one of the bits
1428 in this mask will result in a log-message being emitted.  All logging
1429 can be turned off by calling C<init_level(0)>.
1430
1431 =head2 init_prefix()
1432
1433  ZOOM::Log::init_prefix($0);
1434
1435 Initialises a prefix string to be included in all log-messages.
1436
1437 =head2 init_file()
1438
1439  ZOOM::Log::init_file("/tmp/myapp.log");
1440
1441 Initialises the output file to be used for logging: subsequent
1442 log-messages are written to the nominated file.  If this function is
1443 not called, log-messages are written to the standard error stream.
1444
1445 =head2 init()
1446
1447  ZOOM::Log::init($level, $0, "/tmp/myapp.log");
1448
1449 Initialises the log-level, the logging prefix and the logging output
1450 file in a single operation.
1451
1452 =head2 time_format()
1453
1454  ZOOM::Log::time_format("%Y-%m-%d %H:%M:%S");
1455
1456 Sets the format in which log-messages' timestamps are emitted, by
1457 means of a format-string like that used in the C function
1458 C<strftime()>.  The example above emits year, month, day, hours,
1459 minutes and seconds in big-endian order, such that timestamps can be
1460 sorted lexicographically.
1461
1462 =head2 init_max_size()
1463
1464 (This doesn't seem to work, so I won't bother describing it.)
1465
1466 =head2 log()
1467
1468  ZOOM::Log::log(8192, "reducing to warp-factor $wf");
1469  ZOOM::Log::log("myapp", "starting up with pid ", $$);
1470
1471 Provided that the first argument, log-level, is among the modules
1472 previously established by C<init_level()>, this function emits a
1473 log-message made up of a timestamp, the prefix supplied to
1474 C<init_prefix()>, if any, and the concatenation of all arguments after
1475 the first.  The message is written to the standard output stream, or
1476 to the file previous specified by C<init_file()> if this has been
1477 called.
1478
1479 The log-level argument may be either a numeric value, as returned from
1480 C<module_level()>, or a string containing the module name.
1481
1482 =head1 ASYNCHRONOUS APPLICATIONS
1483
1484 Although asynchronous applications are conceptually complex, the ZOOM
1485 support for them is provided through a very simple interface,
1486 consisting of one option (C<async>), one function (C<ZOOM::event()>),
1487 one Connection method (C<last_event()> and an enumeration
1488 (C<ZOOM::Event>).
1489
1490 The approach is as follows:
1491
1492 =over 4
1493
1494 =item Initialisation
1495
1496 Create several connections to the various servers, each of them having
1497 the option C<async> set, and with whatever additional options are
1498 required - e.g. the piggyback retrieval record-count can be set so
1499 that records will be returned in search responses.
1500
1501 =item Operations
1502
1503 Send searches to the connections, request records, etc.
1504
1505 =item Event harvesting
1506
1507 Repeatedly call C<ZOOM::event()> to discover what responses are being
1508 received from the servers.  Each time this function returns, it
1509 indicates which of the connections has fired; this connection can then
1510 be interrogated with the C<last_event()> method to discover what event
1511 has occurred, and the return value - an element of the C<ZOOM::Event>
1512 enumeration - can be tested to determine what to do next.  For
1513 example, the C<ZEND> event indicates that no further operations are
1514 outstanding on the connection, so any fetched records can now be
1515 immediately obtained.
1516
1517 =back
1518
1519 Here is a very short program (omitting all error-checking!) which
1520 demonstrates this process.  It parallel-searches three servers (or more
1521 of you add them the list), displaying the first record in the
1522 result-set of each server as soon as it becomes available.
1523
1524  use ZOOM;
1525  @servers = ('z3950.loc.gov:7090/Voyager',
1526              'z3950.indexdata.com:210/gils',
1527              'agricola.nal.usda.gov:7190/Voyager');
1528  for ($i = 0; $i < @servers; $i++) {
1529      $z[$i] = new ZOOM::Connection($servers[$i], 0,
1530                                    async => 1, # asynchronous mode
1531                                    count => 1, # piggyback retrieval count
1532                                    preferredRecordSyntax => "usmarc");
1533      $r[$i] = $z[$i]->search_pqf("mineral");
1534  }
1535  while (($i = ZOOM::event(\@z)) != 0) {
1536      $ev = $z[$i-1]->last_event();
1537      print("connection ", $i-1, ": ", ZOOM::event_str($ev), "\n");
1538      if ($ev == ZOOM::Event::ZEND) {
1539          $size = $r[$i-1]->size();
1540          print "connection ", $i-1, ": $size hits\n";
1541          print $r[$i-1]->record(0)->render()
1542              if $size > 0;
1543      }
1544  }
1545
1546 =head1 SEE ALSO
1547
1548 The ZOOM abstract API,
1549 http://zoom.z3950.org/api/zoom-current.html
1550
1551 The C<Net::Z3950::ZOOM> module, included in the same distribution as this one.
1552
1553 The C<Net::Z3950> module, which this one supersedes.
1554 http://perl.z3950.org/
1555
1556 The documentation for the ZOOM-C module of the YAZ Toolkit, which this
1557 module is built on.  Specifically, its lists of options are useful.
1558 http://indexdata.com/yaz/doc/zoom.tkl
1559
1560 The BIB-1 diagnostic set of Z39.50,
1561 http://www.loc.gov/z3950/agency/defns/bib1diag.html
1562
1563 =head1 AUTHOR
1564
1565 Mike Taylor, E<lt>mike@indexdata.comE<gt>
1566
1567 =head1 COPYRIGHT AND LICENCE
1568
1569 Copyright (C) 2005-2014 by Index Data.
1570
1571 This library is free software; you can redistribute it and/or modify
1572 it under the same terms as Perl itself, either Perl version 5.8.4 or,
1573 at your option, any later version of Perl 5 you may have available.
1574
1575 =cut
1576
1577 1;