-
Notifications
You must be signed in to change notification settings - Fork 182
/
HIVQueryHelper.pm
executable file
·2161 lines (1803 loc) · 53.9 KB
/
HIVQueryHelper.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# $Id: HIVQueryHelper.pm 231 2008-12-11 14:32:00Z maj $
#
# BioPerl module for Bio::DB::HIV::HIVQueryHelper
#
# Please direct questions and support issues to <bioperl-l@bioperl.org>
#
# Cared for by Mark A. Jensen <maj@fortinbras.us>
#
# Copyright Mark A. Jensen
#
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=head1 NAME
Bio::DB::HIV::HIVQueryHelper - Routines and packages used by Bio::DB::HIV and
Bio::DB::Query::HIVQuery
=head1 SYNOPSIS
Used in Bio::DB::Query::HIVQuery. No need to use directly.
=head1 DESCRIPTION
C<Bio::DB::HIV::HIVQueryHelper> contains a number of packages for use
by L<Bio::DB::Query::HIVQuery>. Package C<HIVSchema> parses the
C<lanl-schema.xml> file, and allows access to it in the context of the
relational database it represents (see APPENDIX for excruciating
detail). Packages C<QRY>, C<R>, and C<Q> together create the query
string parser that enables NCBI-like queries to be understood by
C<Bio::DB::Query::HIVQuery>. They provide objects and operators to
perform and simplify logical expressions involving C<AND>, C<OR>, and
C<()> and return hash structures that can be handled by
C<Bio::DB::Query::HIVQuery> routines.
=head1 FEEDBACK
=head2 Mailing Lists
User feedback is an integral part of the evolution of this and other
Bioperl modules. Send your comments and suggestions preferably to
the Bioperl mailing list. Your participation is much appreciated.
bioperl-l@bioperl.org - General discussion
http://bioperl.org/wiki/Mailing_lists - About the mailing lists
=head2 Support
Please direct usage questions or support issues to the mailing list:
I<bioperl-l@bioperl.org>
rather than to the module maintainer directly. Many experienced and
reponsive experts will be able look at the problem and quickly
address it. Please include a thorough description of the problem
with code and data examples if at all possible.
=head2 Reporting Bugs
Report bugs to the Bioperl bug tracking system to help us keep track
of the bugs and their resolution. Bug reports can be submitted via
the web:
https://redmine.open-bio.org/projects/bioperl/
=head1 AUTHOR - Mark A. Jensen
Email maj@fortinbras.us
=head1 CONTRIBUTORS
Mark A. Jensen
=head1 APPENDIX
The rest of the documentation details each of the contained packages.
Internal methods are usually preceded with a _
=cut
# Let the code begin...
package Bio::DB::HIV::HIVQueryHelper;
use strict;
use Bio::Root::Root;
# globals
BEGIN {
#exceptions
@Bio::QueryStringSyntax::Exception::ISA = qw( Bio::Root::Exception);
}
1;
=head2 HIVSchema - objects/methods to manipulate a version of the LANL HIV DB schema
=head3 HIVSchema SYNOPSIS
$schema = new HIVSchema( 'lanl-schema.xml' );
@tables = $schema->tables;
@validFields = $schema->fields;
@validAliases = $schema->aliases;
@query_aliases_for_coreceptor = $schema->aliases( 'SEQ_SAMple.SSAM_second_receptor' );
$pk_for_SequenceEntry = $schema->primarykey('SequenceEntry'); # returns 'SequenceEntry.SE_id'
$fk_for_SEQ_SAMple_to_SequenceEntry =
$schema->foreignkey('SEQ_SAMple', 'SequenceEntry'); # returns 'SEQ_SAMple.SSAM_SE_id'
$table = $schema->tablepart('SEQ_SAMple.SSAM_badseq'); # returns 'SEQ_SAMple'
$column = $schema->columnpart('SEQ_SAMple.SSAM_badseq'); # returns 'SSAM_badseq'
=head3 HIVSchema DESCRIPTION
HIVSchema methods are used in L<Bio::DB::Query::HIVQuery> for table,
column, primary/foreign key manipulations based on the observed Los
Alamos HIV Sequence Database (LANL DB) naming conventions for their
CGI parameters. The schema is contained in an XML file
(C<lanl-schema.xml>) which is read into an HIVSchema object, in turn a
property of the HIVQuery object. HIVSchema methods are used to build
correct cgi queries in a way that attempts to preserve the context of
the relational database the query parameters represent.
=cut
package # hide from PAUSE
HIVSchema;
# objects/methods to manipulate a version of the LANL HIV DB schema
# stored in XML
use XML::Simple;
use Bio::Root::Root;
use strict;
### constructor
=head3 HIVSchema CONSTRUCTOR
=head4 HIVSchema::new
Title : new
Usage : $schema = new HIVSchema( "lanl-schema.xml ");
Function:
Example :
Returns : an HIVSchema object
Args : XML filename
=cut
sub new {
my $class = shift;
my @args = @_;
my $self = {};
if ($args[0]) {
$self->{schema_ref} = loadHIVSchema($args[0]);
}
bless($self, $class);
return $self;
}
### object methods
=head3 HIVSchema INSTANCE METHODS
=head4 HIVSchema tables
Title : tables
Usage : $schema->tables()
Function: get all table names in schema
Example :
Returns : array of table names
Args : none
=cut
sub tables {
# return array of all tables in schema
local $_;
my $self = shift;
my $sref = $self->{schema_ref};
Bio::Root::Root->throw("schema not initialized") unless $sref;
my @k = grep(/\./, keys %$sref);
my %ret;
foreach (@k) {
s/\..*$//;
$ret{$_}++;
}
@k = sort keys %ret;
return @k;
}
=head4 HIVSchema columns
Title : columns
Usage : $schema->columns( [$tablename] );
Function: return array of columns for specified table, or all columns in
schema, if called w/o args
Example :
Returns :
Args : tablename or fieldname string
=cut
sub columns {
# return array of columns for specified table
# all columns in schema, if called w/o args
local $_;
my $self = shift;
my ($tbl) = @_;
my $sref = $self->{schema_ref};
Bio::Root::Root->throw("schema not initialized") unless $sref;
# trim column name
$tbl =~ s/\..*$//;
# check if table exists
return () unless grep(/^$tbl$/i, $self->tables);
my @k = sort keys %$sref;
@k = grep (/^$tbl\./i, @k);
foreach (@k) {
s/^$tbl\.//;
}
return @k;
}
=head4 HIVSchema fields
Title : fields
Usage : $schema->fields();
Function: return array of all fields in schema, in format "table.column"
Example :
Returns : array of all fields
Args : none
=cut
sub fields {
# return array of all fields (Table.Column format) in schema
my $self = shift;
my $sref = $self->{schema_ref};
Bio::Root::Root->throw("schema not initialized") unless $sref;
my @k = sort keys %{$sref};
return @k;
}
=head4 HIVSchema options
Title : options
Usage : $schema->options(@fieldnames)
Function: get array of options (i.e., valid match data strings) available
to specified field
Example :
Returns : array of match data strings
Args : [array of] fieldname string[s] in "table.column" format
=cut
sub options {
# return array of options available to specified field
my $self = shift;
my ($sfield) = @_;
my $sref = $self->{schema_ref};
Bio::Root::Root->throw("schema not initialized") unless $sref;
return $$sref{$sfield}{option} ? @{$$sref{$sfield}{option}} : ();
}
=head4 HIVSchema aliases
Title : aliases
Usage : $schema->aliases(@fieldnames)
Function: get array of aliases to specified field[s]
Example :
Returns : array of valid query aliases for fields as spec'd in XML file
Args : [an array of] fieldname[s] in "table.column" format
=cut
sub aliases {
# return array of aliases to specified field
my $self = shift;
my ($sfield) = @_;
my $sref = $self->{schema_ref};
my @ret;
Bio::Root::Root->throw("schema not initialized") unless $sref;
if ($sfield) {
return $$sref{$sfield}{alias} ? @{$$sref{$sfield}{alias}} : ();
}
else { # all valid aliases
map {push @ret, @{$$sref{$_}{alias}} if $$sref{$_}{alias}} $self->fields;
return @ret;
}
}
=head4 HIVSchema ankh
Title : ankh (annotation key hash)
Usage : $schema->ankh(@fieldnames)
Function: return a hash translating fields to annotation keys for the
spec'd fields.
(Annotation keys are used for parsing the tab-delimited response
to Bio::DB::Query::HIVQuery::_do_lanl_request.)
Example :
Returns : hash ref
Args : [an array of] fieldname[s] in "table.column" format
=cut
sub ankh {
# return hash translating sfields to annotation keys for specified sfield(s)
my $self = shift;
my %ret = ();
my @sfields = @_;
my $sref = $self->{schema_ref};
Bio::Root::Root->throw("schema not initialized") unless $sref;
foreach (@sfields) {
next unless $$sref{$_}{ankey};
$ret{$_} = {'ankey'=>$$sref{$_}{ankey},'antype'=>$$sref{$_}{antype}};
}
return %ret;
}
=head4 HIVSchema tablepart
Title : tablepart (alias: tbl)
Usage : $schema->tbl(@fieldnames)
Function: return the portion of the fieldname[s] that refer to the
db table
Example : $schema->tbl('SequenceEntry.SE_id'); # returns 'SequenceEntry'
Returns : table name as string
Args : [an array of] fieldname[s] in "table.column" format
=cut
sub tablepart {
# return the 'Table' part of the specified field(s)
my $self = shift;
my @sfields = @_;
Bio::Root::Root->throw("schema not initialized") unless $self->{schema_ref};
my ($squish,@ret, %ret);
if ($sfields[0] eq '-s') {
# squish : remove duplicates from the returned array
$squish=1;
shift @sfields;
}
foreach (@sfields) {
push @ret, /^(.*)\./;
}
if ($squish) {
# arg order is clobbered
@ret{@ret} = undef;
@ret = keys %ret;
}
return (wantarray ? @ret : $ret[0]);
}
sub tbl {
# tablepart alias
shift->tablepart(@_);
}
=head4 HIVSchema columnpart
Title : columnpart (alias: col)
Usage : $schema->col(@fieldnames)
Function: return the portion of the fieldname[s] that refer to the
db column
Example : $schema->col('SequenceEntry.SE_id'); # returns 'SE_id'
Returns : column name as string
Args : [an array of] fieldname[s] in "table.column" format
=cut
sub columnpart {
# return the 'Column' part of the specified field(s)
my $self = shift;
my @sfields = @_;
Bio::Root::Root->throw("schema not initialized") unless $self->{schema_ref};
my @ret;
foreach (@sfields) {
push @ret, /\.(.*)$/;
}
return (wantarray ? @ret : $ret[0]);
}
sub col {
# columnpart alias
shift->columnpart(@_);
}
=head4 HIVSchema primarykey
Title : primarykey [alias: pk]
Usage : $schema->pk(@tablenames);
Function: return the primary key of the specified table[s], as judged by
the syntax of the table's[s'] fieldnames
Example : $schema->pk('SequenceEntry') # returns 'SequenceEntry.SE_id'
Returns : primary key fieldname[s] in "table.column" format, or null if
no pk exists
Args : [an array of] table name[s] (fieldnames are ok, table part used)
=cut
sub primarykey {
# return the primary key (in Table.Column format) of specified table(s)
my $self = shift;
my @tbl = @_;
my @ret;
Bio::Root::Root->throw("schema not initialized") unless $self->{schema_ref};
foreach my $tbl (@tbl) {
# trim column name
$tbl =~ s/\..*$//;
grep(/^$tbl$/i, $self->tables) ?
push(@ret, grep(/\.[0-9a-zA-Z]+_id/, grep(/$tbl/i,$self->fields))) :
push(@ret, "");
}
return (wantarray ? @ret : $ret[0]);
}
sub pk {
# primarykey alias
shift->primarykey(@_);
}
=head4 HIVSchema foreignkey
Title : foreignkey [alias: fk]
Usage : $schema->fk($intable [, $totable])
Function: return foreign key fieldname in table $intable referring to
table $totable, or all foreign keys in $intable if $totable
unspec'd
Example : $schema->fk('AUthor', 'SequenceEntry'); # returns 'AUthor_AU_SE_id'
Returns : foreign key fieldname[s] in "table.column" format
Args : tablename [, optional foreign table name] (fieldnames are ok,
table part used)
=cut
sub foreignkey {
# return foreign key in in-table ($intbl) to to-table ($totbl)
# or all foreign keys in in-table if to-table not specified
# keys returned in Table.Column format
my $self = shift;
my ($intbl, $totbl) = @_;
Bio::Root::Root->throw("schema not initialized") unless $self->{schema_ref};
# trim col names
$intbl =~ s/\..*$//;
$totbl =~ s/\..*$// if $totbl;
# check if in-table exists
return () unless grep( /^$intbl/i, $self->tables);
my @ret = grep( /$intbl\.(?:[0-9a-zA-Z]+_){2,}id/i, $self->fields);
if ($totbl) {
my $tpk = $self->primarykey($totbl);
return (wantarray ? () : "") unless grep( /^$totbl/i, $self->tables) && $tpk;
($tpk) = ($tpk =~ /\.(.*)$/);
@ret = grep( /$tpk$/, @ret);
return (wantarray ? @ret : $ret[0]);
}
else {
# return all foreign keys in in-table
return @ret;
}
}
sub fk {
# foreignkey alias
shift->foreignkey(@_);
}
=head4 HIVSchema foreigntable
Title : foreigntable [alias ftbl]
Usage : $schema->ftbl( @foreign_key_fieldnames );
Function: return tablename of table that foreign keys points to
Example : $schema->ftbl( 'AUthor.AU_SE_id' ); # returns 'SequenceEntry'
Returns : tablename
Args : [an array of] fieldname[s] in "table.column" format
=cut
sub foreigntable {
# return table name that foreign key(s) point(s) to
my $self = shift;
my @fk = @_;
my @ret;
Bio::Root::Root->throw("schema not initialized") unless $self->{schema_ref};
foreach (@fk) {
my ($mnem, $fmnem) = /\.([0-9a-zA-Z]+)_([0-9a-zA-Z]+)_.*$/;
next unless $mnem && $fmnem;
# lookup based on Table.Column format of fields
my $sf = [grep( /^[0-9a-zA-Z]+\.$fmnem\_/, $self->fields )]->[0];
next unless $sf;
($sf) = ($sf =~ /^([0-9a-zA-Z]+)\./);
push @ret, $sf;
}
return (wantarray ? @ret : $ret[0]);
}
sub ftbl {
# foreigntable alias
shift->foreigntable(@_);
}
=head4 HIVSchema find_join
Title : find_join
Usage : $sch->find_join('Table1', 'Table2')
Function: Retrieves a set of foreign and primary keys (in table.column
format) that represents a join path from Table1 to Table2
Example :
Returns : an array of keys (as table.column strings) -or- an empty
array if Table1 == Table2 -or- undef if no path exists
Args : two table names as strings
=cut
sub find_join {
my $self = shift;
my ($tgt, $tbl) = @_;
my ($stack, $revstack, $found, $revcut) = ([],[], 0, 4);
$self->_find_join_guts($tgt, $tbl, $stack, \$found);
if ($found) {
if (@$stack > $revcut) {
# reverse order of tables, see if a shorter path emerges
$found = 0;
$self->_find_join_guts($tgt, $tbl, $revstack, \$found, 1);
return (@$stack <= @$revstack ? @$stack : @$revstack);
}
return @$stack;
}
else {
return undef;
}
}
=head4 HIVSchema _find_join_guts
Title : _find_join_guts
Usage : $sch->_find_join_guts($table1, $table2, $stackref, \$found, $reverse)
(call with $stackref = [], $found=0)
Function: recursive guts of find_join
Example :
Returns : if a path is found, $found==1 and @$stackref contains the keys
in table.column format representing the path; if a path is not
found, $found == 0 and @$stackref contains garbage
Args : $table1, $table2 : table names as strings
$stackref : an arrayref to an empty array
\$found : a scalar ref to the value 0
$rev : if $rev==1, the arrays of table names will be reversed;
this can give a shorter path if cycles exist in the
schema graph
=cut
sub _find_join_guts {
my $self = shift;
my ($tbl, $tgt, $stack, $found, $rev) = @_;
return () if $tbl eq $tgt;
my $k = $self->pk($tbl);
if ($k) {
# all fks pointing to pk
my @fk2pk = map {
$self->fk($_, $k) || ()
} ($rev ? reverse $self->tables : $self->tables);
# skip keys already on stack
if (@$stack) {
(@$stack == 1) && do {
@fk2pk = grep (!/$$stack[0]/, @fk2pk);
};
(@$stack > 1 ) && do {
@fk2pk = map { my $f=$_; grep(/$f/, @$stack) ? () : $f } @fk2pk;
};
}
foreach my $f2p (@fk2pk) { # tables with fks pointing to pk
push @$stack, $f2p;
if ($self->tbl($f2p) eq $tgt) { # this fk's table is the target
# found it
$$found = 1;
return;
}
else {
#keep looking
$self->_find_join_guts($self->tbl($f2p), $tgt, $stack, $found, $rev);
return if $$found;
}
}
}
# all fks in $tbl
my @fks = ($rev ? reverse $self->fk($tbl) : $self->fk($tbl));
#skip keys already on stack
if (@$stack) {
(@$stack == 1) && do {
@fks = grep(!/$$stack[0]/, @fks);
};
(@$stack > 1) && do {
@fks = map { my $f=$_; grep(/$f/, @$stack) ? () : $f } @fks;
};
}
# all fks in table
if (@fks) {
for my $f (@fks) {
push @$stack, $f;
if ($self->ftbl($f) eq $tgt) { #found it
$$found = 1;
return;
}
else {
$self->_find_join_guts($self->ftbl($f), $tgt, $stack, $found, $rev);
$$found ? return : pop @$stack;
}
}
}
else {
pop @$stack;
return;
}
}
=head4 HIVSchema loadSchema
Title : loadHIVSchema [alias: loadSchema]
Usage : $schema->loadSchema( $XMLfilename )
Function: read (LANL DB) schema spec from XML
Example : $schema->loadSchema('lanl-schema.xml');
Returns : hashref to schema data
Keys are fieldnames in "table.column" format.
Each value is a hashref with the following properties:
{name} : HIVWEB 'table.column' format fieldname,
can be used directly in the cgi query
{aliases} : ref to array containing valid aliases/shortcuts for
{name}; can be used in routines creating the HTML query
{options} : ref to array containing valid matchdata for this field
can be used directly in the HTML query
{ankey} : contains the annotation key for this field used with
Bioperl annotation objects
{..attr..}: ..value_of_attr.. for this field (app-specific metadata)
Args :
=cut
sub loadHIVSchema {
my $fn = shift;
Bio::Root::Root->throw("loadHIVSchema: schema file not found") unless -e $fn;
my $q = XML::Simple->new(ContentKey=>'name',NormalizeSpace=>2,ForceArray=>1);
my %ret;
my $ref = $q->XMLin($fn);
my @sf = keys %{$$ref{sfield}};
foreach (@sf) {
my $h = $$ref{sfield}{$_};
$ret{$_} = $h;
foreach my $ptr ($$h{option}, $$h{alias}) {
if ($ptr) {
# kludge for XMLin: appears to convert to arrays, if there
# exists a tag without content, but to convert to hashes
# with content as key, if all tags possess content
if (ref($ptr) eq 'HASH') {
my @k = keys %{$ptr};
if (grep /desc/, keys %{$ptr->{$k[0]}}) {
# slurp the desc's
$$h{desc} = [ map { $$ptr{$_}->{desc} } @k ];
}
# now overwrite with keys (descs in same order...)
$ptr = [@k];
}
elsif (ref($ptr) eq 'ARRAY') {
$ptr = [map { ref eq 'HASH' ? $_->{name} : $_ } @{$ptr}]
}
else {
1; # stub : doh!
}
}
}
for my $ptr ($$h{ankey}) {
# flatten
my $ank = [keys %{$ptr}]->[0];
if (!defined $ank) {
delete $$h{ankey};
}
else {
$h->{antype} = $ptr->{$ank}{antype};
$ptr = $ank;
}
}
}
return \%ret;
}
sub loadSchema {
my $self = shift;
$self->{schema_ref} = loadHIVSchema(shift);
}
# below, dangerous
=head4 HIVSchema _sfieldh
Title : _sfieldh
Usage : $schema->_sfieldh($fieldname)
Function: get hashref to the specified field hash
Example :
Returns : hashref
Args : fieldname in "table.column" format
=cut
sub _sfieldh {
# return reference to the specified field hash
my $self = shift;
my ($sfield) = @_;
return ${$self->{schema_ref}}{$sfield};
}
1;
=head2 Class QRY - a query algebra for HIVQuery
=head3 QRY SYNOPSIS
$Q = new QRY(
new R(
new Q('coreceptor', 'CXCR4'),
new Q('country', 'ZA')
)
);
QRY::Eq(QRY::And($Q, $Q), $Q); # returns 1
QRY::Eq(QRY::Or($Q, $Q), $Q); # returns 1
$Q2 = $Q1->clone;
$Q2 = new QRY(
new R(
new Q( 'coreceptor', 'CCR5' ),
new Q( 'country', 'ZA')
)
);
(QRY::And($Q, $Q2))->isnull; # returns 1
$Q3 = QRY::Or($Q, $Q2);
print $Q3->A; # prints '(CCR5 CXCR4)[coreceptor] (ZA)[country]'
=head3 QRY DESCRIPTION
The QRY package provides a query parser for
L<Bio::DB::Query::HIVQuery>. Currently, the parser supports AND, OR,
and () operations. The structure of the LANL cgi makes it tricky to
perform NOTs, though this could be implemented if the desire were
great.
Two class methods do the work. C<QRY::_parse_q> does a first-pass
parse of the query string. C<QRY::_make_q> interprets the parse tree
as returned by C<QRY::_parse_q> and produces an array of hash
structures that can be used directly by C<Bio::DB::Query::HIVQuery>
query execution methods. Validation of query fields and options is
performed at the C<Bio::DB::Query::HIVQuery> level, not here.
C<QRY> objects are collections of C<R> (or request) objects, which are
in turn collections of C<Q> (or atomic query) objects. C<Q> objects
represent a query on a single field, with match data options C<OR>ed
together, e.g. C<(A B)[subtype]>. C<R> objects collect C<Q> objects
that could be processed in a single HTTP request; i.e., a set of
atomic queries each having different fields C<AND>ed together, such as
(A B)[subtype] AND ('CCR5')[coreceptor] AND (US CA)[country]
The C<QRY> object collects C<R>s that cannot be reduced (through
logical operations) to a single HTTP request, e.g.
((C)[subtype] AND (SI)[phenotype]) OR ( (D)[subtype] AND (NSI)[phenotype] ),
which cannot be got in one go through the current LANL cgi
implementation (as far as I can tell). The parser will simplify
something like
((C)[subtype] AND (SI)[phenotype]) OR ((C)[subtype] AND (NSI)[phenotype])
to the single request
(C)[subtype] AND (NSI SI)[phenotype]
however.
The operators C<&> and C<|> are overloaded to C<QRY::And> and
C<QRY::Or>, to get Perl precedence and grouping for free. C<bool> is
overloaded to get symbolic tests such as C<if ($QRY) {stuff}>. C<==>
is overloaded with C<QRY::Eq> for convenience. No overloading is done
for C<R> or C<Q>.
=cut
# a query algebra for HIVQuery
#
# Each Q object is an 'atomic' query, written as (data)[field]
# (a b ...)[X] equals (a)[X] | (b)[X] | ...
# Each R object represents a single HTTP request to the db
# contains an array of Q (atomic) objects (q1, q2, ...)
# the R object is interpreted as q1 & q2 & ...
# Each QRY object represents a series of HTTP requests to the db
# contains an array of R (request) objects (R1, R2, ...)
# the QRY object is interpreted as R1 | R2 | ...
#
# & and | operations are specified for each type
package # hide from PAUSE
QRY;
use strict;
$QRY::NULL = new QRY();
use overload
"|" => \&Or,
"&" => \&And,
"bool" => \&Bool,
"==" => \&Eq;
# query language emulator
# supports only AND and OR, any groupings
#
# syntax rules:
# query atom: bareword [field] OR (bareword ...) [field]
# only single bareword allowed between []
# annotation fields in {} (only bareword lists allowed between {})
# () can group query atoms joined by operators (AND or OR)
# () containing only barewords MUST be followed by a field descriptor [field]
# empty [] not allowed
# query atoms joined with AND by default
# barewords are associated (ORed within) the next field descriptor in the line
# follow the parse tree, creating new QRY objects as needed in @q, and
# construct a logical expression using & and | symbols.
# These are overloaded for doing ands and ors on QRY objects;
# to get the final QRY object, eval the resulting expression $q_expr.
# QRY object will be translated into (possibly multiple) hashes
# conforming to HIVQuery parameter requirements.
=head4 QRY _make_q
Title : _make_q
Usage : QRY::_make_q($parsetree)
Function: creates hash structures suitable for HIVQuery from parse tree
returned by QRY::_parse_q
Example :
Returns : array of hashrefs of query specs
Args : a hashref
=cut
sub _make_q {
my $ptree = shift;
my ($q_expr, @q, @an, $query, @dbq);
_make_q_guts($ptree, \$q_expr, \@q, \@an);
$query = eval $q_expr;
throw Bio::Root::Root(-class=>'Bio::Root::Exception',
-text=>$@,
-value=>$q_expr) if $@;
return {} if $query->isnull;
foreach my $rq ($query->requests) {
my $h = {'query'=>{}};
foreach ($rq->atoms) {
my @d = split(/\s+/, $_->dta);
foreach my $d (@d) {
$d =~ s/[+]/ /g; ###! _ to [+]
$d =~ s/'//g;
}
$h->{'query'}{$_->fld} = (@d == 1) ? $d[0] : [@d];
}
$h->{'annot'} = [@an] if @an;
push @dbq, $h;
}
return @dbq;
}
=head4 QRY _make_q_guts
Title : _make_q_guts (Internal class method)
Usage : _make_q_guts($ptree, $q_expr, $qarry, $anarry)
Function: traverses the parse tree returned from QRY::_parse_q, checking
syntax and creating HIVQuery-compliant query structures
Example :
Returns :
Args : $parse_tree (hashref), $query_expression (scalar string ref),
$query_array (array ref : stack for returning query structures),
$annotation_array (array ref : stack for returning annotation
fields)
=cut
sub _make_q_guts {
my ($ptree, $q_expr, $qarry, $anarry) = @_;
my (@words, $o);
eval { # catch
foreach (@{$ptree->{cont}}) {
m{^AND$} && do {
$$q_expr .= "&";
next;
};
m{^OR$} && do {
$$q_expr .= "|";
next;
};
m{^HASH} && do {
for my $dl ($_->{delim}) {
($dl =~ m{\(}) && do {
if (grep /^HASH/, @{$_->{cont}}) {
$$q_expr .= "&" unless !$$q_expr || !length($$q_expr) || (substr($$q_expr, -1, 1) =~ /[&|(]/);
$$q_expr .= "(";
_make_q_guts($_,$q_expr,$qarry,$anarry);
$$q_expr .= ")";
}
else {
my @c;
my $c = join(' ',@{$_->{cont}});
$c =~ s/,/ /g;
Bio::Root::Root->throw("query syntax error: unmatched ['\"]") if (@c = ($c =~ /(['"])/g)) % 2;
@c = split(/\s*(['"])\s*/, $c);
do {
$c = shift @c;
if ($c =~ m{['"]}) {
$c = join('', ($c, shift @c, shift @c));
$c =~ s/\s+/+/g; ###! _ to +
push @words, $c;
}
else {
push @words, split(/\s+/,$c);
}
} while @c;
}
last;
};
($dl =~ m{\[}) && do {
Bio::Root::Root->throw("syntax error: empty field descriptor") unless @{$_->{cont}};
Bio::Root::Root->throw("syntax error: more than one field descriptor in square brackets") unless @{$_->{cont}} == 1;
push @{$qarry}, new QRY( new R( new Q( $_->{cont}->[0], @words)));
# add default operation if nec
$$q_expr .= "&" unless !$$q_expr || !length($$q_expr) || (substr($$q_expr, -1, 1) =~ /[&|(]/);
$$q_expr .= "\$q[".$#$qarry."]";
@words = ();
last;
};
($dl =~ m{\{}) && do {
foreach my $an (@{$_->{cont}}) {
($an =~ /^HASH/) && do {
if ($an->{delim} eq '[') {
push @$anarry, @{$an->{cont}};
}
else {
Bio::Root::Root->throw("query syntax error: only field descriptors (with or without square brackets) allowed in annotation spec");
}
next;
};
do { #else
push @$anarry, $an;
next;
};
}
last;
};
do {
1; #else stub
};
}
next;
};
do { # else, bareword
if ($o) {
$words[-1] .= "+$_"; ####! _ to +
}
else {
push @words, $_;
}
m/['"]/ && ($o = !$o);
};
} # @{ptree->{cont}}
Bio::Root::Root->throw("query syntax error: no search fields specified")
unless $$q_expr =~ /q\[[0-9]+\]/;
};
$@ ?
throw Bio::Root::Root(-class=>'Bio::QueryStringSyntax::Exception',
-text=>$@,
-value=>$$q_expr)
: return 1;
}
=head4 QRY _parse_q
Title : _parse_q
Usage : QRY::_parse_q($query_string)
Function: perform first pass parse of a query string with some syntax
checking, return a parse tree suitable for QRY::_make_q
Example : QRY::_parse_q(" to[be] OR (not to)[be] ");
Returns : hashref
Args : query string
=cut
# parse qry string into a branching tree structure
# each branch tagged by the opening delimiter ( key 'delim' )
# content (tokens and subbranch hashes) placed in l2r order in
# @{p->{cont}}
sub _parse_q {
local $_;
my $qstr = shift;
my $illegal = qr/[^a-zA-Z0-9-_<>=,\.\(\[\{\}\]\)\s'"]/;
my $pdlm = qr/[\{\[\(\)\]\}]/;
my %md = ('('=>')', '['=>']','{'=>'}');
my @tok = grep !/^\s*$/, split /($pdlm)/, $qstr;
return {} unless @tok;