blib/lib/Keystone/Resolver/Database.pm untested

filter: Statementstmt 0.0% 0 / 316 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 520 CC 52 SCAR 33.5
CC
52
Cov
0%
last_insert_id
110.0
_make_cond
56.0
_count
56.0
CRAP 28.4
1 # $Id: Database.pm,v 1.40 2008-04-30 16:57:56 mike Exp $
2  
3 package Keystone::Resolver::Database;
4  
5 use strict;
6 use warnings;
7 use DBI;
8 use Encode; # To decode UTF-8 sequences from DB
9 use Carp;
10 use Scalar::Util;
11 use Keystone::Resolver::Utils qw(encode_hash decode_hash);
12  
13 use Keystone::Resolver::DB::Genre;
14 use Keystone::Resolver::DB::ServiceType;
15 use Keystone::Resolver::DB::Service;
16 use Keystone::Resolver::DB::Serial;
17 use Keystone::Resolver::DB::Domain;
18 use Keystone::Resolver::DB::Site;
19 use Keystone::Resolver::DB::Session;
20 use Keystone::Resolver::DB::User;
21 use Keystone::Resolver::DB::MetadataFormat;
22 use Keystone::Resolver::DB::Provider;
23 use Keystone::Resolver::DB::ServiceTypeRule;
24 use Keystone::Resolver::DB::ServiceRule;
25 use Keystone::Resolver::DB::SerialAlias;
26 use Keystone::Resolver::DB::ServiceSerial;
27 use Keystone::Resolver::DB::GenreServiceType;
28  
29  
30 =head1 NAME
31  
32 Keystone::Resolver::Database - Resource Database for an OpenURL v1.0 resolver
33  
34 =head1 SYNOPSIS
35  
36 $db = new Keystone::Resolver::Database($resolver);
37 $genre = $db->genre_by_mformat("info:ofi/fmt:kev:mtx:journal");
38 print $genre->name();
39  
40 =head1 DESCRIPTION
41  
42 This object represents the Resource Database, or RDB, for an OpenURL
43 resolver. In includes the physical connection information to the
44 underlying database together with application logic at the database
45 level.
46  
47 =head1 METHODS
48  
49 =cut
50  
51  
52 =head2 new()
53  
54 $db = new Keystone::Resolver::Database($resolver, $name);
55 $rwdb = new Keystone::Resolver::Database($resolver, $name, 1);
56  
57 Constructs a new Database for the specified resolver, using the
58 specified database name. If an optional third argument is present and
59 true, then the database is opened in read-write mode rather than the
60 default read-only mode.
61  
62 Read-only and read-write modes are achieved by connecting to the user
63 as one of two different users.
64 In read-only mode, the user named by the C<KRuser> environment
65 variable is used, together with the password specified by C<KRpw>.
66 In read-write mode, the user named by the C<KRrwuser> environment
67 variable is used, together with the password specified by C<KRrwpw>.
68 B<These environment variables must be set of the resolver will not run.>
69  
70 The system administrator must ensure that the values provided for
71 read-write access do match a username (and password) that has
72 read-write access to the resolver database, and ideally that those
73 provided for readonly access do not.
74  
75 The DBMS used (via the DBI framework) defaults to C<mysql>, but this
76 is overridden by the C<KRdbms> environment variable if set.
77  
78 =cut
79  
80 sub new {
81 my $class = shift();
82 my($resolver, $name, $rw) = @_;
83  
84 my($user, $pw);
85 if ($rw) {
86 $user = $ENV{KRrwuser} || die "no KRrwuser defined in environment";
87 $pw = $ENV{KRrwpw} || die "no KRrwpw defined in environment";
88 } else {
89 $user = $ENV{KRuser} || die "no KRuser defined in environment";
90 $pw = $ENV{KRpw} || die "no KRpw defined in environment";
91 }
92  
93 my $dbms = $ENV{KRdbms} || "mysql";
94 my $dbh = DBI->connect_cached("dbi:$dbms:$name", $user, $pw,
95 { RaiseError => 1, AutoCommit => 1 });
96  
97 my $this = bless {
98 resolver => $resolver,
99 dbms => $dbms,
100 dbh => $dbh,
101 cache => {},
102 }, $class;
103  
104 # We don't want the back-reference to the parent object to prevent
105 # its destruction.
106 Scalar::Util::weaken($this->{resolver});
107  
108 $this->log(Keystone::Resolver::LogLevel::LIFECYCLE, "new DB $this with resolver=$resolver");
109  
110 if ($this->oracle()) {
111 # For some reason, this combination makes searching case-blind
112 $this->do("alter session set NLS_COMP=ANSI");
113 $this->do("alter session set NLS_SORT=BINARY_CI");
114 }
115  
116 return $this;
117 }
118  
119  
120 sub DESTROY {
121 my $this = shift();
122 Keystone::Resolver::static_log(Keystone::Resolver::LogLevel::LIFECYCLE,
123 "dead DB $this");
124 }
125  
126  
127 # We need to know if we're Oracle, as all the SQL needs tweaking
128 sub oracle {
129 shift()->{dbms} eq "Oracle";
130 }
131  
132  
133 sub log {
134 my $this = shift();
135 my $resolver = $this->{resolver};
136 if (defined $resolver) {
137 return $resolver->log(@_);
138 } else {
139 warn "weakened {resolver} reference has become undefined: logging @_";
140 }
141 }
142  
143  
144 sub loglookup {
145 my $this = shift();
146 return $this->log(Keystone::Resolver::LogLevel::DBLOOKUP,
147 map { !defined $_ ? "[undef]" :
148 ref $_ ? $_->render() : $_ } @_);
149 }
150  
151  
152 sub genre_by_tag {
153 my $this = shift();
154 my($tag) = @_;
155  
156 my $obj = $this->find1("Genre", tag => $tag);
157 return undef if !defined $obj;
158 $this->loglookup("genre_by_tag($tag) -> ", $obj);
159 return $obj;
160 }
161  
162  
163 sub genre_by_mformat {
164 my $this = shift();
165 my($mformat) = @_;
166  
167 # No doubt this could be optimised, but not using the object model
168 my $mfobj = $this->find1("MetadataFormat", uri => $mformat);
169 return undef if !$mfobj;
170 my $obj = $this->find1("Genre", id => $mfobj->genre_id());
171 $this->loglookup("genre_by_mformat($mformat) -> ", $obj);
172  
173 return $obj;
174 }
175  
176  
177 sub servicetypes_by_genre {
178 my $this = shift();
179 my($genreId) = @_;
180  
181 ### No doubt this could be optimised
182 my @gst = $this->find("GenreServiceType", "service_type_id", genre_id => $genreId);
183 my @ids = map { $_->service_type_id() } @gst;
184 $this->loglookup("servicetypes_by_genre($genreId) -> " . join(", ", @ids));
185 my @refs = ();
186 foreach my $id (@ids) {
187 # There should be no duplicates unless the database is broken
188 my $stype = $this->find1("ServiceType", id => $id)
189 or die "no ServiceType $id";
190 push @refs, $stype;
191 }
192  
193 # Result is sorted lowest priority first
194 return sort { $a->priority() <=> $b->priority() } @refs;
195 }
196  
197  
198 sub servicetypes_by_tags {
199 my $this = shift();
200 my(@tags) = @_;
201  
202 my @obj = $this->find("ServiceType", "priority", tag => \@tags);
203 $this->loglookup("servicetypes_by_tag('@tags') -> " .
204 join(", ", map { $_->id() } @obj));
205 return @obj;
206 }
207  
208  
209 sub services_by_type {
210 my $this = shift();
211 my($stID) = @_;
212  
213 my @obj = $this->find("Service", "priority, tag", service_type_id => $stID);
214 $this->loglookup("services_by_type($stID) -> " .
215 join(", ", map { $_->id() } @obj));
216  
217 # It seems that we have to sort the results ourselves rather than
218 # letting the database do it, because Oracle misinterprets empty
219 # strings as NULL and sorts them to the freakin' end. *sigh*
220 return sort { $a->priority() <=> $b->priority() ||
221 (!defined $a->tag() ? -1 :
222 !defined $b->tag() ? 1 :
223 $a->tag() cmp $b->tag()) } @obj;
224 }
225  
226  
227 sub services_by_tags {
228 my $this = shift();
229 my(@tags) = @_;
230  
231 my @obj = $this->find("Service", "priority", tag => \@tags);
232 $this->loglookup("services_by_tag('@tags') -> " .
233 join(", ", map { $_->id() } @obj));
234 return @obj;
235 }
236  
237  
238 sub service_by_type_and_tag {
239 my $this = shift();
240 my($type, $tag) = @_;
241  
242 my $obj = undef;
243 my $stype = $this->find1("ServiceType", tag => $type);
244 $obj = $this->find1("Service",
245 service_type_id => $stype->id(), tag => $tag)
246 if defined $stype;
247 $this->loglookup("service_by_type_and_tag($type, $tag) -> ",
248 $obj, !defined $stype ? " (unknown service-type)" : "");
249 return $obj;
250 }
251  
252  
253 sub serial {
254 my $this = shift();
255 my($issn, $title) = @_;
256  
257 if (defined $issn) {
258 # Match by ISSN if one is provided and detectable
259 # Normalise spaces and hyphens in ISSN
260 $issn =~ s/\s+//g;
261 $issn =~ s/-//g;
262 my $obj = $this->find1("Serial", issn => $issn);
263 if (defined $obj) {
264 $this->loglookup("serial(issn=$issn) -> ", $obj);
265 return $obj;
266 }
267 }
268  
269 if (!defined $title) {
270 $this->loglookup("serial(no title) NO MATCH");
271 return undef;
272 }
273  
274 # No ISSN match: we need to search for the title instead
275 # Normalise case and whitespace in serial title
276 $title = lc($title);
277 $title =~ s/^\s+//;
278 $title =~ s/\s+$//;
279 $title =~ s/\s+/ /g;
280 my $obj = $this->find1("Serial", name => $title);
281 if (defined $obj) {
282 $this->loglookup("serial(title=$title) -> ", $obj);
283 return $obj;
284 }
285  
286 # No match on primary title: we need to search the aliases
287 my $alias = $this->find1("SerialAlias", alias => $title);
288 if (defined $alias) {
289 $obj = $this->find1("Serial", id => $alias->serial_id());
290 $this->loglookup("serial(alias=$title) -> ", $obj);
291 return $obj;
292 }
293  
294 $this->loglookup("serial(alias=$title) NO MATCH");
295 return undef;
296 }
297  
298  
299 sub service_has_serial {
300 my $this = shift();
301 my($service, $serial) = @_;
302  
303 my $ss = $this->find1("ServiceSerial", service_id => $service->id(),
304 serial_id => $serial->id());
305 my $b = defined $ss ? 1 : 0;
306 $this->loglookup("service_has_serial(", $service, ", ", "$serial) -> $b");
307 return $b;
308 }
309  
310  
311 sub domain_by_name {
312 my $this = shift();
313 my($domain) = @_;
314  
315 my $obj = $this->find1("Domain", domain => $domain);
316 $this->loglookup("domain_by_name($domain) -> ", $obj)
317 if defined $obj;
318  
319 return $obj;
320 }
321  
322  
323 sub site_by_tag {
324 my $this = shift();
325 my($tag) = @_;
326  
327 my $obj = $this->find1("Site", tag => $tag);
328 $this->loglookup("site_by_tag($tag) -> ", $obj)
329 if defined $obj;
330  
331 return $obj;
332 }
333  
334  
335 # Wrappers for finding a single object of a specific type
336 sub session1 { shift()->find1("Keystone::Resolver::DB::Session", @_) }
337 sub user1 { return shift()->find1("Keystone::Resolver::DB::User", @_) }
338  
339  
340 # There is a cache in $this of loaded objects, indexed by the
341 # $class/@conds combination. But in general we can't use this since
342 # we need a way of invalidating the cache when the relevant part of
343 # the database is modified. But since the invalidation bit would have
344 # to be shared between all Apache processes, it would itself need to
345 # be stored in the database, so that a database search would necessary
346 # to determine whether a cached object is invalid. In which case, why
347 # not just blindly do the search afresh each time the linked object is
348 # needed? So the following code does _not_ appear in find1()
349 #
350 # my $index = "$class:" . encode_hash(@conds);
351 # my $obj = $this->{cache}->{$index};
352 # if (defined $obj) {
353 # $this->log(Keystone::Resolver::LogLevel::CACHECHECK,
354 # "reusing cached object $obj");
355 # } else {
356 # $obj = $this->_findraw($class, 1, undef, @conds);
357 # $this->{cache}->{$index} = $obj;
358 # $this->log(Keystone::Resolver::LogLevel::CACHECHECK,
359 # "fetched and cached object $obj");
360 # }
361 #
362 # return $obj;
363  
364  
365 # Returns a SCALAR of the first (hopefully only) matching object
366 sub find1 {
367 my $this = shift();
368 my($class, @conds) = @_;
369  
370 return $this->_findraw($class, 1, undef, @conds);
371 }
372  
373  
374 # Returns an ARRAY of objects matching the conditions
375 sub find {
376 my $this = shift();
377 my($class, $sortby, @conds) = @_;
378  
379 return $this->_findraw($class, 0, $sortby, @conds);
380 }
381  
382  
383 # @conds is a set of (key, value) pairs, with an implicit equality
384 # relation, and all the pairs are ANDed together. $sortby, if
385 # defined, is the order in which to sort the discovered records. If
386 # $single is true, this means to expect a single matching record and
387 # return just that record rather than an array.
388 #
389 sub _findraw {
390 my $this = shift();
391 my($class, $single, $sortby, @conds) = @_;
392 $class = "Keystone::Resolver::DB::$class" if $class !~ /::/;
393  
394 my($cond, $rendered, @values) = $this->_make_cond(@conds);
395 my($sth, undef, $errmsg) = $this->_findcond($class, $cond, $sortby, 1, @values);
396 die "_findraw(): $errmsg" if !defined $sth;
397  
398 my $refref = $sth->fetchall_arrayref();
399 if ($single) {
400 my $table = $class->table();
401 if (@$refref == 0) {
402 $this->log(1, "no $table satisfying $rendered");
403 return undef;
404 } elsif (@$refref > 1) {
405 $this->log(1, scalar(@$refref), " ${table}s satisfying $rendered");
406 }
407 my $ref = $refref->[0];
408 return $class->new($this, map { decode_utf8($_) } @$ref);
409 }
410  
411 return map { $class->new($this, map { decode_utf8($_) } @$_) } @$refref;
412 }
413  
414  
415 sub _make_cond {
416 my $this = shift();
417 my(@conds) = @_;
418  
419 return (undef, "")
420 if !@conds;
421  
422 my(@keys, @values);
423 my $rendered = ""; # used only for error-messages
424 for (my $i = 0; $i < @conds/2; $i++) {
425 my $key = $conds[2*$i];
426 my $value = $conds[2*$i+1];
427 croak "key with value '$value' undefined" if !defined $key;
428 croak "value for key '$key' undefined" if !defined $value;
429  
430 $rendered .= ", " if $i > 0;
431 if (!ref $value) {
432 $rendered .= "$key=$value";
433 push @keys, $key;
434 push @values, $value;
435 } else {
436 $rendered .= "$key=(" . join(" or ", @$value) . ")";
437 push @keys, [ $key, scalar(@$value) ];
438 push @values, @$value;
439 }
440 }
441  
442 my $cond = join(" AND ", map {
443 my $res;
444 if (ref $_) {
445 my($key, $n) = @$_;
446 $res = "(" . join(" OR ", map { $this->quote($key)
447 . " = ?" } (1..$n)) . ")";
448 } else {
449 $res = $this->quote($_) . " = ?";
450 }
451 $res;
452 } @keys);
453  
454 return ($cond, $rendered, @values);
455 }
456  
457  
458 # This is used directly by the Admin UI, but not by the resolver
459 # proper, which instead uses the higher-level methods find1() and
460 # find(), which call this through _findraw().
461 #
462 sub _findcond {
463 my $this = shift();
464 my($class, $cond, $sortby, $nocount, @values) = @_;
465  
466 my $table = $class->table();
467 my @fields = $class->physical_fields();
468 @fields = map { $this->quote($_) } @fields;
469  
470 my $sql = "SELECT " . join(", ", @fields) . " FROM ". $this->quote($table);
471 $sql .= " WHERE $cond" if defined $cond;
472 $sql .= " ORDER BY " . $this->quote($sortby)
473 if defined $sortby;
474  
475 my($sth, $errmsg) = $this->do($sql, @values);
476 return (undef, undef, $errmsg) if !defined $sth;
477  
478 my $count;
479 $count = $this->_count($sth, $table, $cond) if !$nocount;
480  
481 return($sth, $count);
482 }
483  
484  
485 # Here we attempt to discover the number of records satisfying the
486 # query in as efficient a way as possible. There's no reliable
487 # standard way to do this, so we have to pox about with
488 # driver-specific code: some support rows(), some do not.
489 #
490 sub _count {
491 my $this = shift();
492 my($sth, $table, $cond) = @_;
493 my $dbh = $this->{dbh};
494  
495 #warn "driver name is '" . $dbh->{Driver}->{Name} . "'\n";
496  
497 # Exploit especially capable drivers that can count their own rows
498 if ($dbh->{Driver}->{Name} eq "xmysql") {
499 return $sth->rows();
500 }
501  
502 # Some really brain-dead back-ends -- notably the Nearly Wonderful
503 # DBD::CSV -- don't support SELECT COUNT(); so we just do the
504 # actual query twice and damned well count the records. Obviously
505 # very inefficient. So it goes: it'll never happen on a Real
506 # Database.
507 if ($dbh->{Driver}->{Name} eq "CSV") {
508 my $sql = "SELECT " . $this->quote("id") . " FROM " . $this->quote($table);
509 $sql .= " WHERE $cond" if defined $cond;
510 my($sth, $errmsg) = $this->do($sql);
511 die "can't count rows by hand: $errmsg" if !defined $sth;
512 my $count = 0;
513 while ($sth->fetchrow_array()) {
514 $count++;
515 }
516 return $count;
517 }
518  
519 # Default implemetation
520 my $sql = "SELECT COUNT(*) FROM " . $this->quote($table);
521 $sql .= " WHERE $cond" if defined $cond;
522 my $countref = $dbh->selectall_arrayref($sql);
523 die "can't count rows with '$sql': " . $dbh->errstr()
524 if !defined $countref;
525  
526 return $countref->[0]->[0];
527 }
528  
529  
530 # Used by findcond() and _count(), and for INSERT, UPDATE and DELETE
531 # in DB/Object.pm. The intention is that ALL SQL statements executed
532 # by the resolver and its admin UI come through here.
533 #
534 sub do {
535 my $this = shift();
536 my($sql, @values) = @_;
537 my $dbh = $this->{dbh};
538  
539 my $sth = $dbh->prepare($sql);
540 return (undef, $dbh->errstr()) if !$sth;
541 $this->log(Keystone::Resolver::LogLevel::SQL,
542 "do(): $sql [", join(", ", @values), "]");
543 $sth->execute(@values) or return (undef, $dbh->errstr());
544 return $sth;
545 }
546  
547  
548 sub last_insert_id {
549 my $this = shift();
550 my($table) = @_;
551  
552 my $dbh = $this->{dbh};
553 my $dbms = $this->{dbms};
554 if ($dbms eq "mysql") {
555 # last_insert_id() doesn't work for DBD::mysql, but there is a
556 # MySQL-specific hack that we can use instead.
557 return $dbh->{mysql_insertid};
558 } elsif ($dbms eq "Oracle") {
559 my $sql = qq[SELECT "${table}_id_seq".CURRVAL FROM dual];
560 my $sth = $this->do($sql);
561 die "can't find sequence number for Oracle" if !defined $sth;
562 my $refref = $sth->fetchall_arrayref();
563 die "can't extract sequence data for Oracle" if !defined $refref;
564 die "no sequence data for Oracle" if !@$refref;
565 warn "multiple sequence data for Oracle" if @$refref > 1;
566 my $ref = $refref->[0];
567 die "still can't extract sequence data for Oracle" if !defined $ref;
568 die "still no sequence data for Oracle" if !@$ref;
569 warn "still multiple sequence data for Oracle" if @$ref > 1;
570 my $id = $ref->[0];
571 warn "last_insert_id($table) returning $id for Oracle";
572 return $id;
573 } else {
574 # This is _supposed_ to be a generic
575 return $dbh->last_insert_id(undef, undef, $table, "id");
576 }
577 }
578  
579  
580 # Quotes a table-name or column-name for use in an SQL statement
581 # appropriately for the underying RDBMS. Basically, this just means
582 # shoving it in double quotes for Oracle.
583 #
584 sub quote {
585 my $this = shift();
586 my($name) = @_;
587  
588 if (!$this->oracle()) {
589 # Easy!
590 return $name;
591 }
592  
593 # We need to deal with compound ORDER BY specifications such as
594 # priority asc, name
595 # We do this by separately double-quoting the first
596 # space-separated word or each comma-and-maybe-space-separated
597 # component. *sigh*
598  
599 return join(", ", map {
600 my @words = split /\s+/, $_;
601 my $first = shift @words;
602 join(" ", qq["$first"], @words);
603 } split /,\s*/, $name);
604 }
605  
606  
607 1;