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