blib/lib/Bio/DB/Tagger.pm untested

filter: Statementstmt 0.0% 0 / 238 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 69 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 33 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 432 CC 33 SCAR 27.6
CC
33
Cov
0%
new
42.0
_nuke_object
42.0
add_tag
30.0
CRAP 15.9
1 package Bio::DB::Tagger;
2 # $Id$
3  
4 use strict;
5 use warnings;
6 use Carp 'croak';
7 use DBI;
8 use Bio::DB::Tagger::Tag;
9  
10 our $VERSION = '1.00';
11  
12 =head1 NAME
13  
14 Bio::DB::Tagger -- Simple object tagging system
15  
16 =head1 SYNOPSIS
17  
18 use Bio::DB::Tagger;
19 my $tagger = Bio::DB::Tagger->new(-dsn => 'dbi:mysql:tagdb',
20 -create => 1);
21  
22 $tagger->add_tags(-object => $object_name,
23 -tags => \@tags);
24  
25 $tagger->set_tags(-object => $object_name,
26 -key => $object_key,
27 -tags => \@tags);
28  
29 $tagger->add_tag(-object => $object_name,
30 -tag => 'venue',
31 -value => 'mermaid parade',
32 -author => 'lincoln.stein@gmail.com');
33  
34 $tagger->add_tag(-object => $object_name,
35 -tag => $tag);
36  
37 $tagger->add_tag($object_name => $tag);
38  
39 $tagger->clear_tags($object_name); # delete all tags attached to object
40 $tagger->delete_tag($object_name,$tag_name [,$value]); # delete one tag attached to object
41  
42 $tagger->nuke_tag($tag_name); # delete this tag completely
43 $tagger->nuke_object($object_name);
44 $tagger->nuke_author($author_name);
45  
46 my @tags = $tagger->get_tags($object_name [,$author]);
47 print "first tag = $tags[0]\n"; # Tag stringify interface
48 print "tag value = ",$tags[0]->value,"\n"; # object interface
49 print "tag author= ",$tags[0]->author,"\n"; # object interface
50  
51 my $hasit = $tagger->has_tag($object_name,$tag);
52  
53 my @objects = $tagger->search_tag($tag);
54  
55 my @tags = $tagger->tags;
56
57 my $iterator = $tagger->tag_match('prefix');
58 while (my $tag = $iterator->next_tag) { }
59  
60 =head1 DESCRIPTION
61  
62 This is a simple object tagger interface that provides relational
63 support for tagging objects (identified by string IDs) with arbitrary
64 string tags.
65  
66 =head2 METHODS
67  
68 =over 4
69  
70 =item $tagger = Bio::DB::Tagger->new(@args)
71  
72 Constructor for the tagger class. Arguments are:
73  
74 -dsn <dsn> A DBI data source, possibly including host and
75 password information
76  
77 -create <0|1> If true, then database will be initialized with a
78 new schema. Database must already exist.
79  
80 The dsn can be a preopened database handle or a dbi: data source
81 string.
82  
83 =cut
84  
85 sub new {
86 my $class = shift;
87  
88 unshift @_,'-dsn' if @_ == 1;
89 my %args = @_;
90 my $dsn = $args{-dsn};
91 my $create = $args{-create};
92 croak "Usage: $class->new(-dsn=>'dbi:...' [,-create=>1]"
93 unless $dsn;
94  
95 my $dbh = (ref $dsn && $dsn->isa('DBI::db'))
96 ? $dsn
97 : DBI->connect($dsn,undef,undef,{AutoCommit=>1});
98 $dbh or croak "Could not connect to $dsn: ",DBI->errstr;
99
100 my $driver = $dbh->{Driver}{Name};
101 my $package = __PACKAGE__.'::'.$driver;
102
103 unless ($package->can('new') or eval "require $package; 1") {
104 croak ($@,
105 "No Tagger interface for database driver $driver is available. ",
106 "Someone needs to write the package $package");
107 }
108  
109 my $self = bless {dbh=>$dbh},$package;
110  
111 $self->initialize() if $create;
112 return $self;
113 }
114  
115 =item @objects = $tagger->search_tag($tag [,$value])
116  
117 =item $object_arrayref = $tagger->search_tag($tag [,$value])
118  
119 Return all object names and keys that are tagged with "$tag",
120 optionally qualified by tag value $value.
121  
122 =cut
123  
124 sub search_tag {
125 my $self = shift;
126 my ($tag,$value) = @_;
127 my $query = <<END;
128 SELECT distinct oname, okey
129 FROM tag
130 NATURAL JOIN tagname
131 NATURAL JOIN object
132 WHERE tname=?
133 END
134 ;
135 my @bind = ($tag);
136 if (defined $value) {
137 $query .= 'AND tvalue=?';
138 push @bind,$value;
139 }
140  
141 my $arrayref = $self->dbh->prepare($query)
142 or croak $self->dbh->errstr;
143 $arrayref->execute(@bind)
144 or croak $self->dbh->errstr;
145  
146 my @result;
147 while (my ($object,$key) = $arrayref->fetchrow_array) {
148 push @result,
149 Bio::DB::Tagger::Tag->new(-name=>$object,
150 -value=>$key);
151 }
152 return @result;
153 }
154  
155 =item $boolean = $tagger->has_tag($object,$tag [,$value])
156  
157 Returns true if indicated object has the indicated tag, or the
158 indicated combination of tag and value.
159  
160 =cut
161  
162 sub has_tag {
163 my $self = shift;
164 my ($object,$tag,$value) = @_;
165 my $query = <<END;
166 SELECT count(*)
167 FROM tag
168 NATURAL JOIN tagname
169 NATURAL JOIN object
170 WHERE oname=?
171 AND tname=?
172 END
173 ;
174 my $name = ref($tag) ? $tag->name : $tag;
175 my @bind = ($object,$name);
176 if (defined $value) {
177 $query .= 'AND tvalue=?';
178 push @bind,$value;
179 }
180 my ($count) = $self->dbh->selectrow_array($query,{},@bind)
181 or croak $self->dbh->errstr;
182 return $count;
183 }
184  
185 =item @tags = $tagger->get_tag($object,$tag)
186  
187 Returns all the tags of type $tag.
188  
189 =cut
190  
191 sub get_tag {
192 my $self = shift;
193 my ($object,$tag,$value) = @_;
194 my $query = <<END;
195 SELECT distinct tname,tvalue,aname,tmodified
196 FROM tag
197 NATURAL JOIN tagname
198 NATURAL JOIN author
199 NATURAL JOIN object
200 WHERE oname=?
201 AND tname=?
202 END
203 ;
204 my $name = ref($tag) ? $tag->name : $tag;
205 my @bind = ($object,$name);
206  
207 my $sth = $self->dbh->prepare($query)
208 or croak $self->dbh->errstr;
209 $sth->execute(@bind)
210 or croak $self->dbh->errstr;
211 my @result;
212 while (my ($tag,$value,$author,$modified) = $sth->fetchrow_array) {
213 push @result,
214 Bio::DB::Tagger::Tag->new(-name=>$tag,
215 -value=>$value,
216 -author=>$author,
217 -modified=>$modified);
218 }
219 return @result;
220 }
221  
222 =item $tags = $tagger->tags()
223  
224 =item @tags = $tagger->tags()
225  
226 Return a list of all tags in the database. In a list context, returns
227 the list of tags. In an array context, returns an array ref.
228  
229 =cut
230  
231 sub tags {
232 my $self = shift;
233 my $ary = $self->dbh->selectcol_arrayref('SELECT tname FROM tagname');
234 return wantarray ? @$ary : $ary;
235 }
236  
237 =item $iterator = $tagger->tag_match('prefix')
238  
239 Returns an iterator that matches all tags beginning with 'prefix'
240 (case insensitive). Call $iterator->next_tag() to get the next match.
241  
242 =cut
243  
244 sub tag_match {
245 my $self = shift;
246 my $prefix = shift;
247 my $sth = $self->dbh->prepare(<<END) or croak $self->dbh->errstr;
248 SELECT tname
249 FROM tagname
250 WHERE tname LIKE ?
251 ORDER BY tname
252 END
253 ;
254 $prefix =~ s/%/\\%/g;
255 $prefix =~ s/_/\\_/g;
256 $sth->execute($prefix.'%') or croak $sth->errstr;
257 return Bio::DB::Tagger::Iterator->new($sth);
258 }
259  
260 =item $iterator = $tagger->tag_match('prefix')
261  
262 Returns an iterator that matches all tags beginning with 'prefix'
263 (case insensitive). Call $iterator->next_tag() to get the next match.
264  
265 =cut
266  
267 sub author_match {
268 my $self = shift;
269 my $prefix = shift;
270 my $sth = $self->dbh->prepare(<<END) or croak $self->dbh->errstr;
271 SELECT aname
272 FROM author
273 WHERE aname LIKE ?
274 ORDER BY aname
275 END
276 ;
277 $prefix =~ s/%/\\%/g;
278 $prefix =~ s/_/\\_/g;
279 $sth->execute($prefix.'%') or croak $sth->errstr;
280 return Bio::DB::Tagger::Iterator->new($sth);
281 }
282  
283 =item $tags = $tagger->tag_counts()
284  
285 =item @tags = $tagger->tag_counts()
286  
287 Return a set of Bio::DB::Tagger::Tag objects representing all known
288 tags. The tag values correspond to the number of times that tag has
289 been used to tag objects.
290  
291 =cut
292  
293 sub tag_counts {
294 my $self = shift;
295 my $sth = $self->dbh->prepare(<<END) or croak $self->dbh->errstr;
296 SELECT tname,count(tname)
297 FROM tag,tagname
298 WHERE tag.tid=tagname.tid
299 GROUP BY tag.tid
300 END
301 ;
302 $sth->execute() or croak $self->dbh->errstr;
303 my @result;
304 while (my($tagname,$count) = $sth->fetchrow_array) {
305 push @result,
306 Bio::DB::Tagger::Tag->new(-name => $tagname,
307 -value => $count);
308 }
309 return wantarray ? @result : \@result;
310 }
311  
312 =item $result = $tagger->add_tag(@args);
313  
314 Add a tag to the database. The following forms are accepted:
315  
316 $tagger->add_tag($object_name=>$tag);
317  
318 Add a Bio::DB::Tagger::Tag to the object named "$object_name".
319  
320 $tagger->add_tag(-object => $object_name,
321 -tag => $tag);
322  
323 The same as above using -option syntax.
324  
325 $tagger->add_tag(-object => $object_name,
326 -tag => $tagname,
327 -value => $tagvalue,
328 -author => $authorname);
329  
330 Generate the tag from the options provided in B<-tag>, B<-value>
331 (optional) and B<-author> (optional), and then add the tag to the
332 object.
333  
334 Returns true on success.
335  
336 =cut
337  
338 sub add_tag {
339 my $self = shift;
340 my ($objectname,$tag,%args);
341  
342 if (@_ == 2) {
343 $objectname = shift;
344 $tag = shift;
345 } else {
346 %args = @_;
347 $tag = $args{-tag};
348 $objectname = $args{-object};
349 }
350 unless (ref $tag && $tag->isa('Bio::DB::Tagger::Tag')) {
351 $tag = Bio::DB::Tagger::Tag->new(-name => $tag,
352 -value => $args{-value},
353 -author=> $args{-author}
354 );
355 }
356
357 croak 'usage: add_tag(-object=>$object_name,-tag=>$tag)'
358 unless defined $objectname && $tag;
359 return if $self->has_tag($objectname,$tag);
360 $self->_set_tags($objectname,[$tag]);
361 }
362  
363 =item $result = $tagger->set_tags(@args);
364  
365 Set the tags of an object, replacing all previous tags.
366  
367 Arguments: B<-object> Name of the object to tag.
368 B<-tags> List of Bio::DB::Tagger::Tag objects
369  
370 Returns true on success.
371  
372 =cut
373  
374 sub set_tags {
375 my $self = shift;
376 my %args = @_;
377 my $object = $args{-object};
378 my $key = $args{-key};
379 my $tags = $args{-tags};
380 defined $object && $key && $tags && ref $tags eq 'ARRAY'
381 or croak 'Usage: $tagger->set_tags(-object=>$object_name,-key=>$object_key,-tags=>[$tag1,$tag2...])';
382 $self->_set_tags($object,$tags,1,$key);
383 }
384  
385 =item $result = $tagger->set_tag(@args);
386  
387 Set a tag, replacing all previous tags of the same name.
388  
389 Arguments: B<-object> Name of the object to tag.
390 B<-tag> A Bio::DB::Tagger::Tag object, or tag name
391  
392 Returns true on success.
393  
394 =cut
395  
396 sub set_tag {
397 my $self = shift;
398 my %args;
399 if (@_ == 2) {
400 %args = (-object=> shift(),
401 -tag => shift());
402 } else {
403 %args = @_;
404 }
405  
406 my $object = $args{-object};
407 my $tag = $args{-tag};
408 defined $object && $tag
409 or croak 'Usage: $tagger->set_tag(-object=>$object_name,-tag=>$tag)';
410 $tag = Bio::DB::Tagger::Tag->new(-name=>$tag,
411 -value=>$args{-value},
412 -author=>$args{-author}
413 )
414 unless ref $tag;
415 $self->delete_tag($object,$tag);
416 $self->add_tag($object,$tag);
417 }
418  
419 =item $result = $tagger->clear_tags($objectname);
420  
421 Clear all tags from the indicated object. Returns true if the
422 operation was successful.
423  
424 =cut
425  
426 sub clear_tags {
427 my $self = shift;
428 my $objectname = shift;
429 $self->_set_tags($objectname,[],1);
430 }
431  
432 =item $result = $tagger->delete_tag($objectname,$tagname [,$tagvalue]);
433  
434 Clear the one tag from the indicated object, filtering by tagname,
435 optionally by value.
436  
437 =cut
438  
439 sub delete_tag {
440 my $self = shift;
441 my ($objectname,$tagname,$tagvalue) = @_;
442 my $dbh = $self->dbh;
443  
444 $dbh->begin_work;
445  
446 eval {
447 my $query = <<END;
448 DELETE FROM tag
449 USING tag,tagname,object
450 WHERE tag.oid=object.oid
451 AND tag.tid=tagname.tid
452 AND object.oname=?
453 AND tagname.tname=?
454 END
455 ;
456 my @bind = ($objectname,$tagname);
457 if (defined $tagvalue) {
458 $query .= ' AND tag.value=?';
459 push @bind,$tagvalue;
460 }
461 $dbh->do($query,{},@bind) or die $dbh->errstr;
462  
463 # remove defunct tags
464 my ($count) = $dbh->selectrow_array(<<END);
465 SELECT count(*)
466 FROM tag,tagname
467 WHERE tag.tid=tagname.tid
468 AND tagname.tname=?
469 END
470 ;
471 $self->nuke_tag($tagname) if $count == 0;
472 $dbh->commit;
473 };
474 if ($@) {
475 warn $@;
476 $dbh->rollback;
477 return;
478 }
479 return 1;
480 }
481  
482 =item $result = $tagger->nuke_object($objectname);
483  
484 Removes the object named $objectname. Returns true if the operation
485 was successful.
486  
487 =cut
488  
489 sub nuke_object {
490 my $self = shift;
491 my $objectname = shift;
492 $self->_nuke_object($objectname,
493 'object',
494 'oname',
495 'oid');
496 }
497  
498 =item $result = $tagger->nuke_author($authorname);
499  
500 Removes the author named $authorname. Returns true if the operation
501 was successful.
502  
503 =cut
504  
505 sub nuke_author {
506 my $self = shift;
507 my $authorname = shift;
508 $self->_nuke_object($authorname,
509 'author',
510 'aname',
511 'aid');
512 }
513  
514 =item $result = $tagger->nuke_tag($tagname);
515  
516 Removes the tag named $tagname. Returns true if the operation was
517 successful.
518  
519 =cut
520  
521 sub nuke_tag {
522 my $self = shift;
523 my $tagname = shift;
524 $self->_nuke_object($tagname,
525 'tagname',
526 'tname',
527 'tid');
528 }
529  
530 sub _nuke_object {
531 my $self = shift;
532 my ($name,$table,$namefield,$idfield) = @_;
533 my $dbh = $self->dbh;
534  
535 my $in_transaction = !$dbh->{AutoCommit};
536  
537 my $rows = 0;
538 $dbh->begin_work unless $in_transaction;
539 eval {
540 my $query =<<END;
541 DELETE FROM $table,tag
542 USING $table
543 LEFT JOIN tag ON $table.$idfield=tag.$idfield
544 WHERE $table.$namefield=?
545 END
546 ;
547 my $sth = $dbh->prepare($query);
548 $rows = $sth->execute($name);
549 $dbh->commit unless $in_transaction;
550 };
551 if ($@) {
552 die $@ if $in_transaction;
553 warn $@;
554 $dbh->rollback unless $in_transaction;
555 return;
556 }
557 return $rows;
558 }
559  
560 sub _set_tags {
561 my $self = shift;
562 my ($objectname,$tags,$replace,$key) = @_;
563  
564 my $dbh = $self->dbh;
565 $dbh->begin_work;
566 eval {
567 local $dbh->{RaiseError}=1;
568 # create/get object id
569 my $oid = $self->object_to_id($objectname,1,$key);
570 $dbh->do("DELETE FROM tag WHERE oid=$oid")
571 if $replace;
572 for my $tag (@$tags) {
573 my $tid = $self->tag_to_id($tag->name,1);
574 my $aid = $self->author_to_id($tag->author,1);
575 my $value = $tag->value;
576  
577 my $sth = $dbh->prepare(
578 "INSERT INTO tag (oid,tid,aid,tvalue) VALUES (?,?,?,?)"
579 );
580 $sth->execute($oid,$tid,$aid,$value);
581 }
582 $dbh->commit;
583 };
584 if ($@) {
585 warn $@;
586 $dbh->rollback;
587 }
588 }
589  
590 =item @tags = $tagger->get_tags($object_name [,$author])
591  
592 Return all tags assigned to the indicated object, optionally
593 filtering by the author.
594  
595 =cut
596  
597 sub get_tags {
598 my $self = shift;
599 my ($oname,$aname) = @_;
600 my $query = <<END;
601 SELECT distinct tname,tvalue,aname,tmodified
602 FROM tag
603 NATURAL JOIN tagname
604 NATURAL JOIN author
605 NATURAL JOIN object
606 WHERE oname=?
607 END
608 ;
609 my @bind = ($oname);
610 if (defined $aname) {
611 $query .= ' AND aname=?';
612 push @bind,$aname;
613 }
614 my $sth = $self->dbh->prepare($query)
615 or croak $self->dbh->errstr;
616 $sth->execute(@bind)
617 or croak $self->dbh->errstr;
618 my @result;
619 while (my ($tag,$value,$author,$modified) = $sth->fetchrow_array) {
620 push @result,
621 Bio::DB::Tagger::Tag->new(-name=>$tag,
622 -value=>$value,
623 -author=>$author,
624 -modified=>$modified);
625 }
626 return @result;
627 }
628  
629 =item $oid = $tagger->object_to_id($objectname [,$create] [,$key])
630  
631 Fetch the object id (oid) of the object named "$objectname". If the
632 object doesn't exist, and $create is true, will create a new entry for
633 the object in the database.
634  
635 =cut
636  
637 sub object_to_id {
638 my $self = shift;
639 return $self->_name_to_id('object','oid','oname',@_);
640 }
641  
642 =item $tid = $tagger->tag_to_id($tagname [,$create])
643  
644 Fetch the tag id (tid) of the object named "$tagname". If the tag
645 doesn't exist, and $create is true, will create a new entry for the
646 tag in the database.
647  
648 =cut
649  
650 sub tag_to_id {
651 my $self = shift;
652 return $self->_name_to_id('tagname','tid','tname',@_);
653 }
654  
655 =item $aid = $tagger->author_to_id($authorname [,$create])
656  
657 Fetch the author id (aid) of the object named "$authorname". If the
658 tag doesn't exist, and $create is true, will create a new entry for
659 the author in the database.
660  
661 =cut
662  
663 sub author_to_id {
664 my $self = shift;
665 return $self->_name_to_id('author','aid','aname',@_);
666 }
667  
668 sub _name_to_id {
669 my $self = shift;
670 my ($table,$index_col,$name_col,$name,$create,$key) = @_;
671 my ($id) = $self->dbh->selectrow_array(
672 "SELECT $index_col FROM $table WHERE $name_col=?",
673 {},
674 $name);
675 return $id if defined $id;
676 return unless $create;
677  
678 # we get here if oid is undef
679 local $self->dbh->{RaiseError}=1;
680  
681 my $sth = $self->dbh->prepare("INSERT INTO $table ($name_col) VALUES (?)");
682 $sth = $self->dbh->prepare("INSERT INTO $table ($name_col, okey) VALUES (?, $key)")
683 if ($table eq 'object') && (defined $key);
684  
685 $sth->execute($name);
686 # in case someone else got there before us!
687 ($id) = $self->dbh->selectrow_array(
688 "SELECT $index_col FROM $table WHERE $name_col=?",
689 {},
690 $name);
691 return $id;
692 }
693  
694 =item $dbh = $tagger->dbh
695  
696 Return underlying DBI handle.
697  
698 =cut
699  
700 sub dbh { return shift->{dbh} }
701  
702 =item $tagger->initialize
703  
704 Initialize the database with a fresh schema.
705  
706 =cut
707  
708 sub initialize {
709 my $self = shift;
710 my $dbh = $self->dbh;
711 my @statements = $self->_table_definitions;
712 my $result = 1;
713 for my $s (@statements) {
714 next unless $s =~ /\S/;
715 $result &&= $dbh->do($s);
716 }
717 return $result;
718 }
719  
720 =back
721  
722 =cut
723  
724 package Bio::DB::Tagger::Iterator;
725  
726 sub new {
727 my $class = shift;
728 my $sth = shift;
729 return bless {sth=>$sth},ref $class || $class;
730 }
731  
732 sub next_tag {
733 my $self = shift;
734 my ($tag) = $self->{sth}->fetchrow_array or return;
735 return $tag;
736 }
737  
738 sub next { shift->next_tag }
739  
740  
741 =head1 SEE ALSO
742  
743 L<Bio::Graphics::Browser>, L<Bio::DB::SeqFeature::Store>
744  
745 =head1 AUTHOR
746  
747 Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.
748  
749 Copyright (c) 2009 Ontario Institute for Cancer Research
750  
751 This package and its accompanying libraries is free software; you can
752 redistribute it and/or modify it under the terms of the GPL (either
753 version 1, or at your option, any later version) or the Artistic
754 License 2.0. Refer to LICENSE for the full license text. In addition,
755 please see DISCLAIMER.txt for disclaimers of warranty.
756  
757 =cut
758  
759 1;
760  
761 __END__