DBIServer.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« DBIServer/Tutorial.pm ↑ Summary DBIServer/LICENCE.pm »
1 package Net::Z3950::DBIServer;
2  
3 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Data::Dumper; # For debugging only
Subroutine BEGIN: called CC=1 SCAR=0.0
5 0 ▶use Net::Z3950::SimpleServer;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Net::Z3950::OID; # Provided by the SimpleServer package
7 use Net::Z3950::DBIServer::Config;
8 use Net::Z3950::DBIServer::ResultSet;
9 use Net::Z3950::DBIServer::GRS1;
10 use Net::Z3950::DBIServer::XML;
11 use Net::Z3950::DBIServer::MARC;
12 use Net::Z3950::DBIServer::SUTRS;
13 use Net::Z3950::DBIServer::Exception;
14 use strict;
15  
16 use vars qw($VERSION);
17 $VERSION = '1.07';
18  
19  
20 =head1 NAME
21  
22 Net::Z3950::DBIServer - Generic Z39.50-to-Relational Database gateway module
23  
24 =head1 SYNOPSIS
25  
26 use Net::Z3950::DBIServer;
27 $handle = new Net::Z3950::DBIServer($configFile);
28 $handle->launch_server("myAppName", @yazOptions);
29  
30 =head1 DESCRIPTION
31  
32 This module provides a generic, configurable gateway between the
33 Z39.50 information retrieval protocol and pretty much any SQL database
34 you can think of. When the DBIServer server module is running, you
35 can connect your favourite Z39.50 client to it, and issue searches.
36 The gateway receives Z39.50 searches, translates them into SQL
37 queries, executes them against a relational database, translates the
38 resulting rows of SQL tables into Z39.50 records, and sends them back
39 out to the client.
40  
41 The mappings from Z39.50 concepts to SQL and back again are controlled
42 by tables described in L<Net::Z3950::DBIServer::Spec>
43  
44 =head1 METHODS
45  
46 =head2 new()
47  
48 $handle = new Net::Z3950::DBIServer($configFile);
49  
50 Creates and returns a new Z39.50-SQL gateway server, configured to
51 translate back and forth between Z39.50 and SQL concepts by the named
52 configuration file. If the file is invalid, error messages are
53 printed to the standard error stream, and an undefined value is
54 returned.
55  
56 A second, argument may optionally be provided. If it is true, then
57 zSQLgate no-ops, producing logs but not searching in, or even
58 connecting to, the backend database.
59  
60 =cut
61  
62 ### We need to stash our handle in a global due to interface misdesign.
63 my $horribleTemporaryGlobalHandle;
64  
65 sub new {
66 my $class = shift();
67 my($configFile, $noop) = @_;
68  
69 my $config = new Net::Z3950::DBIServer::Config($configFile)
70 or return undef;
71  
72 #{ use Data::Dumper; print Dumper($config); }
73 my $ss = new Net::Z3950::SimpleServer(INIT => \&init_handler,
74 SEARCH => \&search_handler,
75 FETCH => \&fetch_handler);
76  
77 # Delay DBI->open() until Init handler so each process gets its own
78 $horribleTemporaryGlobalHandle = bless { ss => $ss,
79 configFile => $configFile,
80 config => $config,
81 noop => $noop,
82 rs => {}, # mapping of resultSetId to RS objects
83 }, $class;
84 return $horribleTemporaryGlobalHandle;
85 }
86  
87  
88 sub dbi_driver {
89 my $this = shift();
90 my $dbname = $this->{config}->dataSource();
91 if ($dbname =~ /^dbi:(.*?):/i) {
92 return $1;
93 } else {
94 die "can't extract DBI driver from '$dbname'";
95 }
96 }
97  
98 sub init_handler {
99 my $args = shift();
100  
101 warn("INIT: args = {\n" .
102 join("", map { " $_ -> '" . $args->{$_} . "'\n" }
103 sort keys %$args) .
104 "}\n") if 0;
105  
106 $args->{IMP_ID} = "169"; # Mike Taylor's implementor ID
107 $args->{IMP_NAME} = ref($horribleTemporaryGlobalHandle);
108 $args->{IMP_VER} = "zSQLgate $VERSION";
109 $args->{HANDLE} = $horribleTemporaryGlobalHandle;
110 my $this = $args->{HANDLE};
111 my $config = $this->{config};
112  
113 my $dbname = $config->dataSource();
114 my $userName = $config->userName();
115 my $passWord = $config->passWord();
116 #warn "dbname='$dbname', userName='$userName', passWord='$passWord'";
117 if ($this->{noop}) {
118 warn "no-op mode: not connecting to database";
119 } else {
120 $this->{dbh} = DBI->connect($dbname, $userName, $passWord,
121 { RaiseError => 0, AutoCommit => 0 })
122 or die "can't open dataSource '$dbname': " . $DBI::errstr;
123  
124 my $options = $config->options();
125 if ($options) {
126 foreach my $key (sort keys %$options) {
127 my $val = $options->{$key};
128 my $old = $this->{dbh}->{$key};
129 $this->{dbh}->{$key} = $val;
130 warn "set option '$key' to '$val' (was '$old')";
131 }
132 }
133 }
134  
135 ### We'd prefer to report a connect() error politely to the
136 # client, but SimpleServer doesn't seem to have a way to do this
137 # yet. You can pass an error code but no addInfo.
138  
139  
140 # I can't imagine why this isn't the default
141 #$this->{dbh}->{'mysql_enable_utf8'} = 1;
142 warn "UTF8='" . $this->{dbh}->{'mysql_enable_utf8'} . "'";
143 }
144  
145  
146 sub search_handler {
147 my $args = shift();
148  
149 warn "in search_handler()\n";
150 eval {
151 _real_search_handler($args, @_);
152 }; if ($@ && ref $@ && $@->isa('Net::Z3950::DBIServer::Exception')) {
153 $args->{ERR_CODE} = $@->code();
154 $args->{ERR_STR} = $@->addinfo();
155 } elsif ($@) {
156 die $@;
157 }
158 }
159  
160  
161 sub _real_search_handler {
162 my $args = shift();
163 my $this = $args->{HANDLE};
164  
165 $this->_maybe_reload_config();
166 my $dbnames = $args->{DATABASES};
167 ### Should SimpleServer (or something) provide constants for diagnostics?
168 if (@$dbnames == 0) {
169 # Specified combination of databases not supported ... not great!
170 die new Net::Z3950::DBIServer::Exception(23);
171 } elsif (@$dbnames > 1) {
172 # Too many databases specified (addInfo = maximum)
173 die new Net::Z3950::DBIServer::Exception(111, '1');
174 }
175  
176 my $dbname = $dbnames->[0];
177 my $config = $this->{config}->forDb($dbname);
178 if (!defined $config) {
179 # Database does not exist (addInfo = database name)
180 # How is this different from 109 Database unavailable?
181 die new Net::Z3950::DBIServer::Exception(235, $dbname);
182 }
183  
184 my $rpn = $args->{RPN};
185 if (defined $rpn) {
186 #warn "*GFS-generated RPN = " . Dumper($rpn);
187 } else {
188 ### Pathetic hack: improve this radically! :-)
189 #die new Net::Z3950::DBIServer::Exception(107, "CQL:" . $args->{CQL});
190 $rpn = bless {
191 attributeSet => "1.2.840.10003.3.1",
192 query => bless {
193 'attributes' => bless([], 'Net::Z3950::RPN::Attributes'),
194 'term' => $args->{CQL},
195 }, "Net::Z3950::RPN::Term",
196 }, "Net::Z3950::APDU::Query";
197 #warn "*Hand-translated RPN = " . Dumper($rpn);
198 }
199  
200 my $aux = $config->auxiliary();
201 my $tablename = @$aux == 0 ? undef : $config->tablename();
202 my $SQLcond = $rpn->{query}->SQLcond($this, $config->searchSpec(),
203 $rpn->{attributeSet}, $tablename);
204 my $restriction = $config->restriction();
205 $SQLcond = "($SQLcond) AND ($restriction)" if defined $restriction;
206 warn "*generated SQL condition '$SQLcond'\n";
207 my $rs = new Net::Z3950::DBIServer::ResultSet($this, $config, $SQLcond);
208 my $setname = $args->{SETNAME};
209 $this->{rs}->{$setname} = $rs;
210 $args->{HITS} = $rs->count();
211 }
212  
213  
214 sub fetch_handler {
215 my $args = shift();
216 my $this = $args->{HANDLE};
217  
218 my $offset = $args->{OFFSET};
219 my $setname = $args->{SETNAME};
220 my $rs = $this->{rs}->{$setname};
221  
222 eval {
223 die new Net::Z3950::DBIServer::Exception(30, $setname)
224 if !defined $rs;
225 $this->_maybe_reload_config();
226 my $dataSpec = $rs->config()->dataSpec();
227 #print Dumper($dataSpec);
228 my $hashref = $rs->fetch($offset-1);
229 #warn "record $offset = " . Dumper($hashref);
230 my($record, $schema) = _format($hashref, $args->{REQ_FORM}, $dataSpec);
231 $args->{RECORD} = $record;
232 $args->{SCHEMA} = $schema if defined $schema;
233 }; if ($@ && ref $@ && $@->isa('Net::Z3950::DBIServer::Exception')) {
234 $args->{ERR_CODE} = $@->code();
235 $args->{ERR_STR} = $@->addinfo();
236 } elsif ($@) {
237 die $@;
238 }
239 }
240  
241  
242 # PRIVATE to fetch_handler()
243 sub _format {
244 my($hashref, $recsyn, $dataSpec) = @_;
245  
246 # I'm sure there's a more OO way to make this switch ...
247 if ($recsyn eq Net::Z3950::OID::grs1 && defined $dataSpec->{GRS1}) {
248 return Net::Z3950::DBIServer::GRS1::format($hashref,
249 $dataSpec->{GRS1});
250 } elsif ($recsyn eq Net::Z3950::OID::xml && defined $dataSpec->{XML}) {
251 return Net::Z3950::DBIServer::XML::format($hashref,
252 $dataSpec->{XML});
253 } elsif ($recsyn eq Net::Z3950::OID::usmarc && defined $dataSpec->{MARC}) {
254 return Net::Z3950::DBIServer::MARC::format($hashref,
255 $dataSpec->{MARC});
256 } elsif ($recsyn eq Net::Z3950::OID::sutrs) {
257 return Net::Z3950::DBIServer::SUTRS::format($hashref,
258 $dataSpec->{SUTRS})
259 if defined $dataSpec->{SUTRS};
260 # Fall back to hardwired SUTRS formatting, for debugging only
261 return join('', map { my $v = $hashref->{$_};
262 defined $v ? "$_: $v\n" : "$_ undefined\n" }
263 sort keys %$hashref);
264 } else {
265 my @supported = ("SUTRS");
266 push @supported, "XML" if defined $dataSpec->{XML};
267 push @supported, "GRS1" if defined $dataSpec->{GRS1};
268 push @supported, "MARC" if defined $dataSpec->{MARC};
269 die new Net::Z3950::DBIServer::Exception(238, join(",", @supported));
270 }
271 }
272  
273  
274 # Here we just add the SQLcond() method to the class that we want.
275 # This is an unconventional alternative to a big switch statement in a
276 # single recursive SQLcond() function, but it's elegant and Perl
277 # allows it, so there.
278 #
279 # All these methods are in some sense private to our search handler.
280  
281 package Net::Z3950::RPN::And;
282 sub SQLcond {
283 my $this = shift();
284  
285 return "(" . ($this->[0]->SQLcond(@_) . ") AND (" .
286 $this->[1]->SQLcond(@_)) . ")";
287 }
288  
289  
290 package Net::Z3950::RPN::Or;
291 sub SQLcond {
292 my $this = shift();
293  
294 return "(" . ($this->[0]->SQLcond(@_) . ") OR (" .
295 $this->[1]->SQLcond(@_)) . ")";
296 }
297  
298  
299 package Net::Z3950::RPN::AndNot;
300 sub SQLcond {
301 my $this = shift();
302  
303 return "(" . ($this->[0]->SQLcond(@_) . ") AND NOT (" .
304 $this->[1]->SQLcond(@_)) . ")";
305 }
306  
307  
308 package Net::Z3950::RPN::Term;
309 sub SQLcond {
310 my $this = shift();
311 my($server, $config, $attributeSet, $tablename) = @_;
312  
313 my %attributes;
314 my $defaultAttrs = $config->{"*defaultattrs"};
315 if (@{ $this->{attributes} } == 0 && defined $defaultAttrs) {
316 foreach my $type (keys %$defaultAttrs) {
317 $attributes{$type} = {
318 attributeSet => "1.2.840.10003.3.1", ### fixed BIB-1!
319 attributeType => $type,
320 attributeValue => $defaultAttrs->{$type},
321 };
322 }
323 }
324  
325 foreach my $attr (@{ $this->{attributes} }) {
326 # There's no diagnostic for multiple attributes of the same
327 # type, so we just ignore them :-)
328 my $type = $attr->{attributeType};
329 $attributes{$type} = $attr;
330 }
331 ### BIB-1/AA assumption (pretty much warranted! :-)
332 my $use = $attributes{1};
333 my $posVal = $attributes{3}->{attributeValue};
334  
335 # Use attribute required but not supplied
336 die new Net::Z3950::DBIServer::Exception(116)
337 if !defined $use;
338 my $val = $use->{attributeValue};
339 $attributeSet = $use->{attributeSet} if defined $use->{attributeSet};
340  
341 # We now have an attribute set and an access point within it
342 my $accessSpec = $config->accessPoint($attributeSet, $val);
343  
344 # Unsupported Use attribute
345 die new Net::Z3950::DBIServer::Exception(114, $val)
346 if !defined $accessSpec;
347  
348 # Special case for fulltext searching: relation etc. are ignored
349 if (defined $posVal && $posVal == 3 && $accessSpec->{fulltext}) {
350 my $term = $this->{term};
351 $term = uc($term) if $accessSpec->{uppercase};
352 my @fields;
353 my $cols = $accessSpec->{columnname};
354 foreach my $col (split /\s*,\s*/, $cols) {
355 $col = "$tablename.$col" if defined $tablename && $col !~ /\./;
356 push @fields, $col;
357 }
358  
359 ### We should handle this kind of backend-specific encoding in
360 # a more generic way, probably using Oracle-specific and
361 # MySQL-specific implementations of an abstract class.
362 if ($server->dbi_driver() eq "Oracle") {
363 return ("(" . join(" or ", map {
364 "CONTAINS($_, " . sqlquote("%$term%") . ") > 0"
365 } @fields) .
366 ")");
367 } else {
368 # MySQL syntax
369 return "match (" . join(", ", @fields) . ") " .
370 "against (" . sqlquote($term) . ")";
371 }
372 }
373  
374 my $relation = relation($attributeSet, \%attributes);
375 my $term = term($attributeSet, \%attributes, $this->{term});
376 $term = uc($term) if $accessSpec->{uppercase};
377 ### We're completely ignoring structure (4) and
378 # completeness (6) attributes, in part because I don't honestly
379 # feel 100% that I know what they mean.
380 if ($term =~ /%/) {
381 ### What does it mean to search (e.g.) < left-truncated term?
382 die new Net::Z3950::DBIServer::Exception(123,
383 "relation other than '=' with truncated term ($term)")
384 if $relation ne "=";
385 $relation = "LIKE";
386 }
387  
388 # We may have multiple comma-separated columns: split 'em up.
389 my $cols = $accessSpec->{columnname};
390 my @conds;
391 foreach my $col (split /\s*,\s*/, $cols) {
392 $col = "$tablename.$col" if defined $tablename && $col !~ /\./;
393 push @conds, $col . " " . $relation . " " . sqlquote($term);
394 }
395  
396 return $conds[0] if @conds == 1;
397 return "(" . join(" OR ", @conds) . ")";
398 }
399  
400 sub sqlquote {
401 my($term) = @_;
402  
403 $term =~ s/['']/''/g;
404 return "'" . $term . "'";
405 }
406  
407  
408  
409 sub relation {
410 my($attributeSet, $attributes) = @_;
411  
412 ### Should check for utility-set attributes as well as BIB-1
413 my $attr = $attributes->{2};
414 return "=" if !defined $attr;
415 my $val = $attr->{attributeValue};
416  
417 my @rel = qw(< <= = >= > <>);
418 my $rel = $rel[$val-1];
419 if (!defined $rel) {
420 # Maybe we should try harder on the others?
421 # 100 = phonetic
422 # 101 = stem
423 # 102 = relevance
424 # 103 = AlwaysMatches
425 die new Net::Z3950::DBIServer::Exception(117, $val);
426 }
427  
428 return $rel;
429 }
430  
431  
432 sub term {
433 my($attributeSet, $attributes, $rawterm) = @_;
434  
435 ### Should check for utility-set attributes as well as BIB-1
436 my $attr = $attributes->{5};
437 return $rawterm if !defined $attr;
438 my $val = $attr->{attributeValue};
439  
440 if ($val == 1) {
441 return $rawterm . "%";
442 } elsif ($val == 2) {
443 return "%" . $rawterm;
444 } elsif ($val == 3) {
445 # For MySQL only, we could use this kind of hack:
446 # column regexp "^fish[ \t]|[ \t]fish[ \t]|[ \t]fish$";
447 # ###
448 # We should make backend-specific plugins that know how to do
449 # this kind of thing, providing callbacks to interpret
450 # completeness, full-text searching, and counting.
451 return "%" . $rawterm . "%";
452 } elsif ($val == 100) {
453 return $rawterm;
454 } elsif ($val == 101) {
455 $rawterm =~ tr/#/%/;
456 return $rawterm;
457 }
458  
459 # What do the others mean? Can we implement them?
460 # 102 = regExpr-1
461 # 103 = regExpr-2
462 die new Net::Z3950::DBIServer::Exception(120, $val);
463 }
464  
465  
466 # We now return you to your scheduled programmes ...
467 package Net::Z3950::DBIServer;
468  
469  
470 sub _maybe_reload_config {
471 my $this = shift();
472  
473 my $configFile = $this->{configFile};
474 my @s = stat($configFile) or die "can't stat '$configFile': $!";
475 my $mtime = $s[9];
476  
477 if ($mtime > $this->{config}->{"*timeStamp"}) {
478 warn "configuation file '$configFile' changed: reloading\n";
479 $this->{config} = new Net::Z3950::DBIServer::Config($configFile)
480 or die "can't compile new configuration";
481 }
482 }
483  
484  
485 =head2 launch_server()
486  
487 $handle->launch_server("myAppName", @yazOptions);
488  
489 Launches the Z39.50-SQL gateway server C<$handle>, using the specified
490 string as an identifier in any log messages, and with its Z39.50
491 server behaviour controlled by C<@yazOptions> as described in the YAZ
492 manual at
493 http://www.indexdata.com/yaz/doc/server.invocation.php
494 and also in
495 L<Net::Z3950::DBIServer::Run>
496  
497 This method never returns unless an error occurs.
498  
499 =cut
500  
501 sub launch_server {
502 my $this = shift();
503 my($logIdent, @yazOptions) = @_;
504  
505 $this->{ss}->launch_server($logIdent, @yazOptions);
506 }
507  
508  
509 =head1 AUTHOR
510  
511 Mike Taylor E<lt>mike@miketaylor.org.ukE<gt>
512  
513 First version Saturday 2nd February 2002.
514  
515 =head1 SEE ALSO
516  
517 L<Net::Z3950::DBIServer::Spec>
518 describes the format of the configuration files which specify this
519 module's behaviour.
520  
521 L<Net::Z3950::DBIServer::Config>
522 describes the API to the configuration file parser.
523  
524 L<Net::Z3950::DBIServer::ResultSet>
525 describes the API to the internal representation of result sets.
526  
527 L<Net::Z3950::DBIServer::GRS1>
528 describes the API to the GRS1 record formatter.
529  
530 L<Net::Z3950::DBIServer::XML>
531 describes the API to the XML record formatter.
532  
533 L<Net::Z3950::DBIServer::Exception>
534 describes the simple exception objects used to represent Bib-1
535 diagnostics.
536  
537 =cut
538  
539  
540 1;
« DBIServer/Tutorial.pm ↑ Summary DBIServer/LICENCE.pm »