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