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