8ff754bb506b68ac07c115e0ee388b88b45bf1e4
[ZOOM-Perl-moved-to-github.git] / samples / zoom / zselect
1 #!/usr/bin/perl -w
2
3 # $Id: zselect,v 1.3 2007-04-18 11:18:08 mike Exp $
4
5 # Example command-line:
6 #       ./zselect -t q localhost:3313/IR-Explain---1 "net.port=3950" "concat(zeerex:serverInfo/zeerex:host, ':', zeerex:serverInfo/zeerex:port, '/', zeerex:serverInfo/zeerex:database)"
7
8 use strict;
9 use warnings;
10 use Getopt::Std;
11 use ZOOM;
12 use XML::LibXML;
13 use XML::LibXML::XPathContext;
14
15 my %opts = (t => "p");
16 if (!getopts('t:', \%opts) || @ARGV != 3) {
17     print STDERR "Usage: $0 [-t queryType] <target> <query> <xpath>
18 Query types:
19         p       Query is in prefix query format (PQF) [default]
20         c       Query is in CCL, sent directly to server
21         q       Query is in CQL, sent directly to server
22         C       Query is in CCL, translated on client side
23         Q       Query is in CQL, translated on client side
24 ";
25     exit 1;
26 }
27
28 my($target, $qstring, $xpath) = @ARGV;
29 my $type = $opts{t};
30 my %type2class = (
31                   p => "PQF",
32                   c => "CCL",   # Bizarrely, not yet implemented in ZOOM
33                   q => "CQL",
34                   C => "CCL2RPN",
35                   Q => "CQL2RPN",
36                   );
37 my $class = $type2class{$type};
38 if (!defined $class) {
39     print STDERR "$0: unrecognised query type '$type'\n";
40     exit 2;
41 }
42
43 my $conn = new ZOOM::Connection($target);
44 my $query = "ZOOM::Query::$class"->new($qstring, $conn);
45 $conn->option(presentChunk => 50);
46 my $rs = $conn->search($query);
47 my $n = $rs->size();
48 #print "found $n record", ($n==1 ? "" : "s"), "\n";
49
50 $rs->option(preferredRecordSyntax => "xml");
51 $conn->option(elementSetName => "zeerex");
52 my $parser = new XML::LibXML();
53
54 foreach my $i (1..$n) {
55     my $rec = $rs->record($i-1);
56     my $xml = $rec->render();
57     my $doc = $parser->parse_string($xml);
58     my $root = $doc->getDocumentElement();
59     my $xc = XML::LibXML::XPathContext->new($root);
60     register_namespaces($xc);
61     print $xc->find($xpath), "\n";
62 }
63
64
65 # I feel really bad about having to have a hardwired list of supported
66 # namespaces, but since it's entirely the fault of LibXML's retarded
67 # lack of proper namespace support in its XPath handling, I am not
68 # going to let it spoil my day.
69 #
70 sub register_namespaces {
71     my($xc) = @_;
72     $xc->registerNs(zeerex => 'http://explain.z3950.org/dtd/2.0/');
73     $xc->registerNs(irspy => 'http://indexdata.com/irspy/1.0');
74     # More to come
75 }