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